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
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
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: , where the subscript indicates the base.
(Unsigned) 5 bit binary integers are restricted to the interval . 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.