Home > Software design >  How to get each digit of a template integral type in its native base?
How to get each digit of a template integral type in its native base?

Time:03-29

I am working on an implementation of Radix sort for arrays of integral types. Using the numeric_limits functions provided by the standard library, I am able to learn about the native base representation of any given integral type using numeric_limits::radix, and the maximum amount of digits in that base that the type can hold using numeric_limits::digits. In order to implement radix sort optimally, I need to extract the value of each of those digits in turn for each of the elements of the array. Is there some standard, or at least common, way to do this? In case it matters, I am using C 20 and do not care about backwards compatibility with older revisions of the standard, only maximum interoperability with other C 20 code.

CodePudding user response:

If you want to iterate through the digits of the number number expressed with radix radix, in order from least-to-greatest significant digits, then a loop like the following would work. This loop assumes that number is a type that supports division and modulus, and that these operations are purely integer operations (fractions are removed):

auto curr_val = number; //Copy the number, since we're going to modify it.
while(curr_val != 0)
{
  auto curr_digit = curr_val % radix;
  curr_val = curr_val / radix; //Integer division.
}

Note that this works regardless of the representation of number in whatever internal representation the type uses. So even if numeric_limits<int>::radix is 2, this will work for iterating through the way number would be represented in base-10.

CodePudding user response:

If you are only working with integer type that uses radix 2, you can use bitset to extract each digit:

auto i = 384762132;
std::bitset<std::numeric_limits<decltype(i)>::digits> b(i);
std::cout << b;     // 0010110111011110000000100010100
std::cout << b[4];  // 1(prints 4th 0-indexed lsb)
  • Related