<<< Back to the Linux Tips Index

8th October 2016

Converting to Binary

To convert 87 to binary:

012510214387
01010111
1286432168421

The trick here is that (working right to left) you keep halving the number (round down if odd) until you get to 1, and then mark any odd numbers as "1", and any even numbers as "0". This gives you 01010111, or 87.

To break it down in a little more detail:

1.87 / 2 = 43 (rounding down). 87 is odd, so leave a 1._______1
2.43 / 2 = 21 (rounding down). 43 is odd, so leave a 1.______1_
3.21 / 2 = 10 (rounding down). 21 is odd, so leave a 1._____1__
4.10 / 2 = 5. 10 is even, so leave a 0.____0___
5.5 / 2 = 2 (rounding down). 5 is odd, so leave a 1.___1____
6.2 / 2 = 1. 2 is even, so leave a 0.__0_____
7.1 / 2 = 1. 1 is odd, so leave a 1, and finish, as we've got down to 1._1______
8.Anything else is zero; you can add an 8th line to make it up to a full byte.0_______
Answer - The top result goes on the right, the bottom is on the left:01010111

.

Invest in your career. Buy my Shell Scripting Tutorial today:

.

Steve Parker - Linux / DevOps Consultant
Share on Twitter Share on Facebook Share on LinkedIn Share on Identi.ca Share on StumbleUpon