I have to convert a binary number like for example unsigned int bin_number = 10101010
into its decimal representation (i.e. 170
) as quickly as possible
Since C++11 (even if C++11 is more limited than C++14 in that regard), function can be constexpr
so avoid necessity of template
to have compile time value.
Here a version C++14 compatible:
constexpr unsigned binary_to_decimal(unsigned num)
{
unsigned res = 0;
while (num)
{
res = 10 * res + num % 10;
num /= 10;
}
return res;
}
And for literals, you can even use binary literals since C++14:
0b1010'1010 // or 0b10101010 without separator