Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert hexadecimal numbers to binary in C++?

Tags:

c++

hex

binary

I am taking a beginning C++ class, and would like to convert letters between hex representations and binary. I can manage to print out the hex numbers using:

for(char c = 'a'; c <= 'z'; c++){
    cout << hex << (int)c;
}

But I can't do the same for binary. There is no std::bin that I can use to convert the decimal numbers to binary.

like image 643
chustar Avatar asked Jan 27 '09 14:01

chustar


2 Answers

Like so:

for(char c = 'a'; c <= 'z'; c++){
        std::bitset<sizeof(char) * CHAR_BIT> binary(c); //sizeof() returns bytes, not bits!
        std::cout << "Letter: " << c << "\t";
        std::cout << "Hex: " << std::hex << (int)c << "\t";
        std::cout << "Binary: " << binary << std::endl;
    }
like image 121
Harper Shelby Avatar answered Sep 28 '22 17:09

Harper Shelby


There isn't a binary io manipulator in C++. You need to perform the coversion by hand, probably by using bitshift operators. The actual conversion isn't a difficult task so should be within the capabilities of a beginner at C++ (whereas the fact that it's not included in the standard library may not be :))

Edit: A lot of others have put up examples, so I'm going to give my preferred method

void OutputBinary(std::ostream& out, char character)
{
  for (int i = sizeof(character) - 1; i >= 0; --i)
  {
    out << (character >> i) & 1;
  }
}

This could also be potentially templated to any numeric type.

like image 23
workmad3 Avatar answered Sep 28 '22 18:09

workmad3