So, I'm looking at making a test to binary program. Once it's done, I then want to look at the assembler that gets generated for learning purposes. Is there a simple way to do this, or do I need to do a bunch of
1 2 3
if(input == 'a')
cout << "01100001";
...
I realize that for my purposes, I would likely be fine with just a few, but, I'm kind of a perfectionist so I can't just half way do a program. This approach would be rather tedious, so I was just curious if someone could point me to some handy built in feature for this :D
Characters are numbers, so printing 'a' in binary is just as hard as printing 97 in binary. There is just one way to convert numbers to some base. That's using / and % operators (though when dealing with binary, these can become >> and &). If you can do it with decimal, you can do it with binary too.
As for built in, I don't think there is. Maybe in C libraries? This is weird, because there are methods to print in hex or oct and bin is not any different.
Hmm I actually meant text to binary, not sure if this makes a difference in your answers or not. I had it explained right in my post, just not the title.
Apart from overriding several operators and to provide direct access to the bits, bitsets have the feature of being able to be constructed from and converted to both integer values and binary strings (see constructor, bitset::to_ulong and bitset::to_string).
http://www.cplusplus.com/reference/stl/bitset/bitset/ ^ Example from constructor reference
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// constructing bitsets
#include <iostream>
#include <string>
#include <bitset>
usingnamespace std;
int main ()
{
bitset<10> first; // empty bitset
bitset<10> second (120ul); // initialize from unsigned long
bitset<10> third (string("01011")); // initialize from string
return 0;
}
bitset reference wrote:
They can also be directly inserted and extracted from streams in binary format.