views:

6438

answers:

6

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. Help? Thanks.

+4  A: 

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
AndreasT
+2  A: 

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

freespace
Just realised what a terrible pun I made... sorry :P
freespace
*groan* Yeah, terrible pun.
Andrei Krotkov
A: 

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;


        }
    }
}
Nathan Fellman
+1  A: 

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
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
+25  A: 

Like so:

for(char c = 'a'; c <= 'z'; c++){
     std::bitset<sizeof(char) * 8> 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
I never knew about this! This is exactly what the OP wanted, and I learned something new myself. Upvote!
Andrei Krotkov
Although it would probably be best to make it std::bitset<sizeof(char)> just in case.
Andrei Krotkov
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
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
@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
Warning: sizeof (char) is 1, not 8.
Arkadiy
This doesn't seem to work in Visual Studio. It keeps saying "bitset not a member of 'std'".
chustar
@chustar: did you #include <bitset> ?
Harper Shelby
@Harper Shelby ahhhhh! Thanks. Works now.
chustar
+1.It seems you can learn C++ tricks even after years of programming. ;-)
neuro
sizeof(char) you must be joking...
AndreasT
A: 

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.
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
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