 # How can I write the binary equivalent of a number?

## Question

How can I write the binary equivalent of a number?

To write any number in binary, add the necessary powers of 2 until you’ve got your number. This is easy enough for small numbers, but not feasible for larger ones. For a better method, check out this video tutorial on converting decimal to binary!

4 Likes

This video really helped me out, thanks!

5 Likes

Take any number and divide it in half repeatedly disregarding remainders along the way until you get to 1. Write each answer to the left of the previous answer. Under each answer you write 1 if the answer is odd and 0 if the answer is even.

Example:

``````Write 2019 in binary.

1   3   7   15    31    63    126    252   504   1009   2019  - Repeatedly half 2019 until you get to 1,
disregard remainders
1   1   1    1     1     1      0      0     0      1      1  - Write 1 under odd answers, 0 under even.

Answer: 2019 in binary is 0b11111100011.
``````
20 Likes

Another good video with another method of converting a decimal number to Binary using 2-4-8-16-32-64-128 bits places

3 Likes

Thanks a lot.I got It after a day trying to get it from all over the place.I rember thats how I was taught back in college.

Using the known length of the binary, we can use successive right shifts and bitwise AND to parse out the bits…

``````>>> from math import log2, floor
>>> n = floor(log2(x))
>>> m = '0b'
>>> while n >= 0:
m += str(x >> n & 1)
n -= 1

>>> m
'0b11111100011'
>>> int(m, 2)
2019
>>>
``````

As you’ve already spent a day learning how to do it on paper, now you have a starting point for doing it with logic. There are any number of ways to achieve this. Another day or two spent on it will not be lost time.

1 Like