DEV Community

Avinash DV
Avinash DV

Posted on

Understand the decimal to binary conversion

Image description

To simply put take the below example

decimal :
120
By basic maths 0 is in 1’s place, 2 is in 10’s place, 1 is in 100’s place
In total, we call it as One hundered and twenty one

binary :
8 4 2 1
1 1 1 1 = 15

As we can see, by using 3 places in decimal we can write all numbers that fall under 100’s place, till 999

But In contrast, we need 4 places in binary just to write 2 digits that too ≤ 15
To write 255(2⁸) we need 8 places and so on.

Image description

You may ask, why can’t we use decimal instead of binary, I’m using decimal numbers all the time in my code and it is working fine!!!!

Ans: Computers only understand 1’s and 0’s which are binary, so whatever we write let it be characters, numbers should be converted to binary as stated above, to be able to run.

if we declare x = 19780 in our code
computer should allocate memory like 2¹⁵ bits = 32768 bits to store it.
whereas 2¹⁴ = 16384 and 19780 can’t fit in 2¹⁴

Same goes for characters/words/sentences as well. Next time you declare variables in your code think of this conversion and avoid un-necessary declarations that could take up the space which makes your code slow.

Top comments (0)