Converting to base 2!

Hello Everyone!

I am currently trying to use bitwise operators in a program of mine for school. However I am unsure on how to convert a number such as 22 from base 10 to base 2. Could someone please give me some ideas on how to do this? Any help is greatly appreciated!
Similar topic: http://www.cplusplus.com/forum/general/22953/


There's no conversion necessary. Numbers are numbers. The only difference is how they're printed to the screen.

1
2
3
4
5
6
7
8
int foo = 5;

// foo is now five.
//  it is not "decimal 5"
//  or "binary 5"
//  it's just 5.
//    you don't convert a number from one kind of number base
//  to another.  The computer just treats it like a number. 


The only thing where the base really matters is when you print the number. I'm not entirely sure but I think you can just use setbase to print the number as binary:

1
2
3
4
5
cout << 5; // prints five as decimal... ie:  "5"
cout << setbase(2) << 5;  // prints five as binary... ie:  "101"

// note I didn't test this code.  the setbase reference page says
//  you should only use 8, 10, or 16 as a base, but that seems ridiculous 
Topic archived. No new replies allowed.