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
Using templates you can solve this problem at compile-time.
template
struct binary
{
static unsigned const value =
binary::value << 1 | num % 10;
};
// Specialization for zero
template<>
struct binary<0>
{ static unsigned const value = 0; };
The binary template is instantiated again with a smaller num
, until num
reaches zero and the specialization is used as a termination condition.
Example: std::cout << binary<10101010>::value;
For run-time problem:
unsigned binary_to_decimal(unsigned num)
{
unsigned res = 0;
for(int i = 0; num > 0; ++i)
{
if((num % 10) == 1)
res += (1 << i);
num /= 10;
}
return res;
}