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? What is the best algorithm?
Using Doubling Write down the binary number. Starting from the left, double your previous total and add the current digit. Double your current total and add the next leftmost digit. Repeat the previous step.
An easy method of converting decimal to binary number equivalents is to write down the decimal number and to continually divide-by-2 (two) to give a result and a remainder of either a “1” or a “0” until the final result equals zero. So for example.
Converting decimal integer to binary To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order.
2^4 * 1 + 2^3 * 0 + 2^2 *1 + 2^1 * 0 + 2^0 * 1 = 21. Therefore, the answer is 21.
Using templates you can solve this problem at compile-time.
template<unsigned long num>
struct binary
{
static unsigned const value =
binary<num/10>::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;
}
Well, if this "number" is actually a string gotten from some source (read from a file or from a user) that you converted into a number (thinking it to be more appropriate for an actual number), which is quite likely, you can use a std::bitset
to do the conversion:
#include <bitset>
unsigned int number = std::bitset<32>("10101010").to_ulong();
(Of course the 32
here is implementation-defined and might be more appropriately written as std::numeric_limits<unsigned int>::digits
.)
But if it is really a number (integer variable) in the (very) first place you could do:
#include <string>
unsigned int number = std::bitset<32>(std::to_string(bin_number)).to_ulong();
(using C++11's to_string
) But this will probably not be the most efficient way anymore, as others have presented more efficient algorithms based on numbers. But as said, I doubt that you really get this number as an actual integer variable in the very first place, but rather read it from some text file or from the user.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With