anything to binary

Hey all!

I was trying to create a decimal to binary converter in c++ (and phailed misorably)
I wanted to ask, has anyone created a bynary to text and text to binary converter and could share the source? i want to build a program that can convert anything to anything.
Input functions do that for you. Note that numbers are stored in bits, that means already binary. You just have to read them the right way.
1
2
3
4
5
int number;
for(int i = sizeof(int)-1; i >= 0; i--){
    if(number & (1<<i)) cout<<'1';
    else cout<<'0';
}
A text (string) to binary converter is found in the sourcecode section: http://www.cplusplus.com/src/
A number to binary is found in C++ std library: http://www.cplusplus.com/reference/stl/bitset/
What does the " (number & (1<<i)) " bit mean? I haven't seen that syntax before.
A little research suggests that the '&' is being used as the boolean AND binary operator... That makes sense, so it's performing the bitwise AND operation on 'number' and whatever '(1<<i)' evaluates to.

I know '<<' as the insertion operator. '1' isn't a stream variable. Any ideas?
1 in decimal is 000...00001 in binary.

1 << i shifts the binary representation of 1 i bits to the left.

number & (1 << i ) therefore zeroes out all bits in number but leaves the ith bit unchanged (LSB is bit 0).
shift operator...Gotcha. Thanks.
Topic archived. No new replies allowed.