How can I write the binary equivalent of a number?
Answer
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!
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.
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.