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

38,883

Solution 1

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;
    }

Solution 2

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.

Solution 3

For bit of variety, you can also do it using a 16 element look up table.

Solution 4

You can easily write a mapping between the hex charachters an their binary 'nibbles':

std::string HexCharToNibble( char c ) {
switch (c) {
  case '0': return "0000";
  case '1': return "0001";
  //... fill in the rest
  case 'f': return "1111";
  default: assert(false); return "bad input";
};

Solution 5

You can do something like this:

for(char c = 'a'; c <= 'z'; c++){
    // char is 8 bits.  print 4 bits
    // at a time, starting with the MSB
    for (int i = 4; i>=0; i-=4) {
        switch (((int)c >> i) & 0xf) {
            case 0:
                cout << "0000";
                break;
            case 1:
                cout << "0001";
                break;
            .
            .
            .
            case 0xf:
                cout << "1111";
                break;


        }
    }
}
Share:
38,883
chustar
Author by

chustar

I just hit 1500 reputation! - Wait, no I didn't... - Haha, yes I did!

Updated on September 25, 2020

Comments

  • chustar
    chustar over 3 years

    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.

  • Andrei Krotkov
    Andrei Krotkov over 15 years
    groan Yeah, terrible pun.
  • Andrei Krotkov
    Andrei Krotkov over 15 years
    This version should definitely be done using a lookup table. The fact that the original code takes a char would be confusing as well.
  • Andrei Krotkov
    Andrei Krotkov over 15 years
    I never knew about this! This is exactly what the OP wanted, and I learned something new myself. Upvote!
  • Andrei Krotkov
    Andrei Krotkov over 15 years
    Although it would probably be best to make it std::bitset<sizeof(char)> just in case.
  • chustar
    chustar over 15 years
    It is an assignment, and as long as I understand how to do it, or how/why it works, does it really matter if its from the internet or the TA?
  • rmeador
    rmeador over 15 years
    wow... that's really cool. I wish I could vote up more than once. Still, despite the awesomeness of your answer, shame on you for providing code for a homework question.
  • chustar
    chustar over 15 years
    Is this correct? std::bitset<8> binary(c) converts the character to its 8bit binary representation and stores that in a variable called binary?
  • Edi
    Edi over 15 years
    @rmeador: there were already several answers - so adding one that (hopefully) teaches a bit more about the STL can't be worse, can it? @chustar: It creates a std::bitset (typically stored as an array) of length 8, and populates the set with the bit values of the binary representation.
  • Nathan Fellman
    Nathan Fellman over 15 years
    Besides, Ted, given Harper Shelby's answer above that taught me (and judging by the comments, a few other people too) something new and useful, I think this question has earned its upvote
  • Admin
    Admin over 15 years
    Warning: sizeof (char) is 1, not 8.
  • chustar
    chustar over 15 years
    This doesn't seem to work in Visual Studio. It keeps saying "bitset not a member of 'std'".
  • Edi
    Edi over 15 years
    @chustar: did you #include <bitset> ?
  • chustar
    chustar over 15 years
    @Harper Shelby ahhhhh! Thanks. Works now.
  • neuro
    neuro over 14 years
    +1.It seems you can learn C++ tricks even after years of programming. ;-)
  • AndreasT
    AndreasT over 14 years
    and here again sizeof(character) ?? Did you guys c&p this from an example with int?
  • Matteo
    Matteo almost 12 years
    @HarperShelby - and if I want to go the other way around?suppose I might want to get the hexadecimal character corresponding to 8 bits...Thks in advance, sorry for bothering on an old question! ;)
  • unwind
    unwind over 11 years
    Sounds like you should include <climits> and use CHAR_BIT to get rid of that 8.
  • Geoffroy
    Geoffroy over 11 years
    @unwind moreover when nothing says a byte will always have 8 bits :)