# Thread: convert single numbers to 5 bit binary

1. ## convert single numbers to 5 bit binary

hello, I would like to know if a single number such as 8 or 4 can be converted into a 5 bit binary numbers and if so, how? I'm not sure if I am barking up the wrong tree, if I am then my mistake, sorry.
many thanks
rolf

2. You can convert any number from 0 to 31 inclusive into a 5-bit binary number. Here's the easy way to do it:

1. Can you subtract 16 from the number and get a positive result? If yes, the first bit is 1, and your new number is the result. If no, leave the number unchanged, and the first bit is 0.

2. From the result of Step 1, can you subtract 8 and get a positive result? If yes, the second bit is 1, and your new number is the result. If no, leave the number unchanged, and the second bit is 0.

Continue doing this, marching down the powers of 2, until you get to 1. That corresponds to the last bit. Then you stop.

Example: $23_{10} = 10111_{2}=1\times 2^{4}+0\times 2^{3}+1\times 2^{2}+1\times 2^{1}+1\times 2^{0}$, where the subscript indicates the base.

3. Originally Posted by rolfharris
hello, I would like to know if a single number such as 8 or 4 can be converted into a 5 bit binary numbers and if so, how? I'm not sure if I am barking up the wrong tree, if I am then my mistake, sorry.
many thanks
rolf
(Unsigned) 5 bit binary integers are restricted to the interval $[0, 2^{5-1}]$. Here is another way to convert to binary besides what Ackbeet mentioned:

For convenience I use the % or "mod" operator commonly used in computer languages; a % b gives the remainder when a is divided by b.

Also, I'll use \ to indicate integer division, which is floor(a/b).

Consider the integer 13.

13 % 2 = 1

Current string: 1

13 \ 2 = 6

6 % 2 = 0

Current string: 01

6 \ 2 = 3

3 % 2 = 1

Current string: 101

3 \ 2 = 1

1 % 2 = 1

Current string: 1101

Finished.

Edit: For clarity, what I'm doing is bit shifting, but it can be done for any base, for example base 3 or base 16.

4. many thanks all!

5. You're very welcome. Have a good one!