12

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.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
chustar
  • 12,225
  • 24
  • 81
  • 119

6 Answers6

49

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;
    }
Harper Shelby
  • 16,475
  • 2
  • 44
  • 51
  • 3
    I never knew about this! This is exactly what the OP wanted, and I learned something new myself. Upvote! – Andrei Krotkov Jan 27 '09 at 14:50
  • 1
    Although it would probably be best to make it std::bitset just in case. – Andrei Krotkov Jan 27 '09 at 14:51
  • 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. – rmeador Jan 27 '09 at 14:59
  • Is this correct? std::bitset<8> binary(c) converts the character to its 8bit binary representation and stores that in a variable called binary? – chustar Jan 27 '09 at 15:11
  • @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. – Harper Shelby Jan 27 '09 at 15:26
  • Warning: sizeof (char) is 1, not 8. –  Jan 27 '09 at 15:46
  • This doesn't seem to work in Visual Studio. It keeps saying "bitset not a member of 'std'". – chustar Jan 27 '09 at 16:52
  • 2
    @chustar: did you #include ? – Harper Shelby Jan 27 '09 at 17:25
  • @Harper Shelby ahhhhh! Thanks. Works now. – chustar Jan 27 '09 at 19:16
  • +1.It seems you can learn C++ tricks even after years of programming. ;-) – neuro Oct 21 '09 at 13:58
  • @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! ;) – Matteo Jun 03 '12 at 20:40
  • 2
    Sounds like you should include `` and use `CHAR_BIT` to get rid of that 8. – unwind Sep 17 '12 at 13:23
  • @unwind moreover when nothing says a byte will always have 8 bits :) – Jaffa Sep 17 '12 at 13:29
5

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.

workmad3
  • 25,101
  • 4
  • 35
  • 56
4

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

freespace
  • 16,529
  • 4
  • 36
  • 58
2

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";
};
xtofl
  • 40,723
  • 12
  • 105
  • 192
  • 2
    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 Jan 27 '09 at 14:49
1

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;


        }
    }
}
Graeme Perrow
  • 56,086
  • 21
  • 82
  • 121
Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319
0

This sounds like an assignment, in which case you really should ask your teacher for help. Soliciting solutions to homework from the internet isn't really going to help you in the long run (unless you are going into project management).

Answering chustar (the OQ'er) in the comments, I'd have to agree that if you understand how to do it, how/why it works,and how to figure it out yourself in the future, then yes, that would be a good thing.

However, the answer he marked "correct" puts the lie to that argument. It contains nothing but code, prefaced with the words "Like so". It's pretty clear that what the OQ'er was looking for was not for an explanation, but for someone to write his code for him.

T.E.D.
  • 44,016
  • 10
  • 73
  • 134
  • 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? – chustar Jan 27 '09 at 14:57
  • 3
    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 – Nathan Fellman Jan 27 '09 at 15:36