Search This Blog

Tuesday, October 27, 2009

C++, Decimal to Binary to Hex

1. convert decimal to binary, use long division, and read the remainder backward
http://www.wikihow.com/Convert-from-Decimal-to-Binary
2. convert the binary to hex, group 4 bits at once and covert them
3. convert the hex to binary, expand each hex to 4-bit binary

#include
#include
#include
#include
using namespace std;

vector dec_to_binary(int dec)
{
vector v;
while (dec != 0){
//insert is not good here, forcing all elements
// to move after begin
//v.insert(v.begin(),dec%2);
//usr push_back is better
v.push_back(dec%2);
cout << dec/2 << "," << dec%2 << endl;
dec = dec/2 ; //integer division, e.g 77/2 = 38
}

copy(v.begin(),v.end(),ostream_iterator(cout,""));
cout << endl;
//reverse the order, easy to read as big-endian
//v.assign(v.rbegin(), v.rend()); //bug!, assgin and iterator to itself
vector v2(v.rbegin(), v.rend());
cout << endl;
return v2;
}

void use_bitset(int dec)
{
// 8 bits in each byte
bitset<8*sizeof(int)> bs(dec);
cout << bs << endl;
}

int main()
{
vector v = dec_to_binary(1234);
copy(v.begin(),v.end(),ostream_iterator(cout,""));
cout << endl;

cout << "binary:";
use_bitset(1234);

cout << "hex:"<< hex << 1234;
}

No comments: