Decimal-to-binary

All I need is a program that will switch from decimal numbers to binary. And it would be easy to do that using strings and so on, but all that I'm allowed to use is the binary and (&) and left shift (>>).
That is, only assuming that our systems are already in binary, and with the help of &, >>.

And I just have no idea how to do it. :(
34 to binary

34/2 = 17 remainder = 0
17/2 = 8 remainder = 1
8/2 = 4 remainder = 0
4/2 = 2 remainder = 0
2/2 = 1 remainder = 0
1/2 = 0 remainder = 1

34 = 100010

hope this helps... use while loop
I knew this, but the only thing I'm allowed to use is the binary and (&) and left shift (>>).
Use another value as a mask, its purpose is to select just one bit at a time from the value.
34 to binary
mask = 1

x =      34        34 & 1 = 0
x >> 1 = 17        17 & 1 = 1
x >> 1 =  8         8 & 1 = 0
x >> 1 =  4         4 & 1 = 0
x >> 1 =  2         2 & 1 = 0
x >> 1 =  1         1 & 1 = 1
x >> 1 =  0 stop

Above, the digits are generated in reverse order.

There is another approach, where the mask is given an big initial value which selects the bit at the left-hand side of the value, and the mask itself is shifted right by 1 position each time. This gives the digits in the correct order (with a little thought) but also may give a lot of leading zeros which may or may not be wanted.

By the way, >> is the shift-right operator (not left).
Last edited on
Topic archived. No new replies allowed.