Binary is a system that governs how all electronic devices function, allowing their hardware and software to communicate and operate. Without Binary, computers including your PC, gaming console, laptop, phone, fridge TV and everything else that uses a PCB (printed circuit board) and software, would not exist.
While you will probably never need to know how Binary works or that it even exists to use these electronic devices, you will need to have a basic understanding of it, if you want to further your career as a coding developer, as well as being a network engineer.
It is also essential to understand Binary, in order to use the decimal.Decimal module in Python, as well as why Floating Point numbers sometimes output a whole lot of decimal places when using the Python Arithmetic Operators (such as Addition, Subtraction, Multiplication Division, Modulus, Exponentiation and Floor Division).
For that reason, this tutorial is going to cover the basics of Binary, including what it is, how to count in Binary (as well as the Decimal system) and how to use Python to easily find the Binary value of any Decimal value.
NOTE: This tutorial requires that Python is already installed, as well as an IDE (Integrated Development Environment), such as PyCharm. It’s also recommended that you have a basic understanding of How to Use Python if this is your first time learning Python, as well as Python Variables and Data Types.
With that said, let’s get started with this free tutorial on Convert Decimal to Binary in Python.
What is Binary?
Computers only understand 0 and 1.
This is known as Binary and it is how every computer that uses software and digital circuitry hardware, knows how to function and communicate.
The Binary System is a numerical system that functions almost identically to the Decimal Number System, which we use everyday in our math.
There are two main difference between the Binary and Decimal systems:
- The Decimal System uses the digits 0 through 9, while the Binary System only uses 0 and 1,
- In Binary, each digit is referred to as a bit, which is an assigned pattern of binary digits to each character, instruction, etc.
- The Decimal System therefore uses the number 10 as its base (Ten numbers : 0,1,2,3,4,5,6,7,8,9), while the binary system uses a base 2 (Two numbers : 0,1).
Apart from these differences, Arithmetic Operations in Binary such as addition, subtraction, multiplication, and division, are all computed using the same rules as the Decimal System.
Due to its ease of implementation in digital circuits using logic gates, almost all modern technology and computers use the binary system .
This is because It’s much simpler to design hardware that only needs to detect on of two states, being ON or OFF:
- ON = 1
- OFF = 0
These are known as States (ON State or OFF State), which can then also be translated and used in other conditions such as true/false, present/absent, etc.
If we were to use the Decimal System in computer circuitry and software, it would require hardware that is able to detect 10 states for the digits 0 through 9, and this would be much more complicated and prone to greater errors.
To better understand this we need to first understand how to count in both the decimal and binary systems using columns.
How to Count in Binary and Decimal Systems
As the decimal and Binary systems are very similar, counting in either of them is almost the same, although there are a few differences,
As Binary only consists of two base numbers (0,1) it counts differently to the Decimal System which has ten base numbers (0,1,2,3,4,5,6,7,8,9), although it technically follows the same rules when counting in either of them.
With that said, let’s take a look at how to count in both the Decimal and Binary systems using columns.
How to Count using the Decimal System
When counting using the Decimal System, we need to follow three simple rules:
- Increase the RIGHT Column by increments of 1 (one)
- The Columns to the LEFT carry their value down until it reaches 9 (nine)
- Once a Column reaches 9, it resets to 0 (zero)
This might sound a bit confusing, but it’s actually very simple.
To start counting in Decimals, we start counting from the smallest number, which is 0.
We then increment that value by 1 each time, as we continue on, to the next value as follows:
- 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9
Once we reach the 10th value (which is 9, as 0 is the 1st value), we run out of digits in this 1st Column.
We then add a 2nd Column to the left of the 1st Column.
The 1st Column then gets reset to 0 as we increment the next, 2nd Column to the left with a 1, resulting in what we know as the number 10 (ten)
We then continue to add the value 1 (carry down – rule 2) in the 2nd Column next to each digit of the 1st Column, until we again reach 9 in the 1st Column again.
Once we reach 9 again, the value 1 in the 2nd Column increments one value up to 2, resulting in what we know as the number 20 (twenty).
We then follow this same procedure to reach 30, 50, etc until we reach 99. Once we reach 99, both the 1st and 2nd Column reset to 0 as we add a 3rd Column
We again increment the 3rd Column with a 1, resulting in what we know as the number 100 (one-hundred)
The 1st Column continues to increment up by one value again, while the 2nd Column remains at 0 and the 3rd column remains at 1. This gives us the number 101 to 109.
Once we reach this point, the 1st Column again resets to 0, the 2nd Column increments up one value to 1, while the 3rd Column remains at 1, resulting in what we know as the number 110 (one-hundred and ten).
This procedure then continues and repeats itself endlessly to create as big of a number as required from 1,000,000 (one million) to 1,000,000,000 (one billion) and so forth.
How to Count using the Binary System
The rules of counting using the Decimal System apply in the same way when counting in Binary, except it only has 2 base values, being 0 (zero) and 1 (one).
- Increase the RIGHT Column by increments of 1 (one)
- The Columns to the LEFT carry their value down until it reaches 1 (one)
- Once a Column reaches 1, it resets to 0 (zero)
When counting using the Binary System we again start with our 1st Column, starting with 0, incrementing one value up to 1.
As the Binary System only consists of two base numbers and not ten like the Decimal system, we reset the 1st Column much earlier, after reaching 1, back to 0.
Once we reset the 1st Column to 0, we again create a 2nd Column, starting with the value 1. As we increment the 1st Column up one value it tells us to carry down the value of 1 along the 2nd Column, resulting in the binary value of 11
As both the 1st Column and 2nd Columns need to be reset back to 0 resets back to 0, we create a 3rd Column with the value 1, resulting in a binary value of 100.
This process now simply repeats itself. We increment the 1st Column by 1, meaning that everything in the columns to its left carry their values down. Once the 1st Column resets, the 2nd Column to its left increments up one value.
If the 2nd Column increments one up, the 3rd Column carries its value down, until the 2nd Column resets, at which point the 3rd Column will increment one value up and so forth.
Once all 3 columns reach a value of 1, resulting in the Binary value of 111, they all need to reset back to 0, at which point we introduce the 4th Column with the value of 1 resulting in binary 1000.
The process then again repeats itself until we again reach a binary value of 1111, at which point we would reset all comuns back to 0 and introduce a 5th Column with the value 1.
If we then take the Decimal values and align them with the corresponding Binary values, we are able to see what binary numbers computers associate with the related decimal numbers.
In other words:
- 0 in Decimal = 0 in Binary
- 1 in Decimal = 1 in Binary
- 3 in Decimal = 11 in Binary
- 4 in Decimal = 100 in Binary
- 5 in Decimal = 101 in Binary
- 6 in Decimal = 110 in Binary
- 7 in Decimal = 111 in Binary
- 8 in Decimal = 1000 in Binary
- 9 in Decimal = 1001 in Binary
- 10 in Decimal = 1010 in Binary
- etc.
How to find a Binary Number using Python
There are several ways in which we can use Python to calculate any Binary number from a Decimal number for us.
One of these is using the Python Modulus Operator and the other is using a Python For Loop.
Let’s take a look at how to do this.
How to find a Binary Number using Python Modulus Operator
We can easily calculate or find a Binary number using the Python Modulus Operator.
For example, let’s say we wanted to know the Binary number of the Decimal number 13.
To do this, we would use the following Python code.
import functools #import function tool for lambda equation to change Tuple to Int
decimal = 13
binary_num_4 = decimal % 2 # 13 % 2 = 1
binary_num_3 = int(decimal/2) % 2 # 13÷2 = 6. Therefore 6 % 2 = 0
binary_num_2 = int((decimal/2) /2) % 2 # Above, then 6÷2 = 3. Therefore 3 % 2 = 1
binary_num_1 = int(((decimal/2) /2) /2) % 2 # Above, then 3÷2 = 1. Therefore 1 % 2 = 1
binary_num = binary_num_1, binary_num_2, binary_num_3, binary_num_4 # Reverse order for correct Binary number
print(binary_num)
#>> (1, 1, 0, 1) # Result in a Tuple
int_result = functools.reduce(lambda sub, ele: sub * 10 + ele, binary_num) # Change Tuple to Int
print(int_result)
#>> 1101
While this might look complicated, it’s actually quite simple when broken down, so let’s do that:
- import functools: This is required for the lambda equation at the end, in order to change the Tuple to an Integer
- Decimal: is simply the decimal number that we want Python to find the Binary number of, which in this example is 13.
- binary_num_4: Here we use the Modulus Operator to calculate the remainder between the Dividend (13) and the Divisor (2), because 2 as this is the Base value of Binary.
- This leaves us with a remainder value of 1, which will be the last value in our final binary number, (as we will be reversing the final output results later on).
- binary_num_3: In order to calculate the next Binary number, we need to first find a new Dividend value.
- To do this we take the original Dividend (13) and simply divide this by 2, which outputs a result of 6.5.
- However, we cannot use a Floating Point number, to calculate Binary, so we will use the Python int() Function to remove all decimal values and only store the whole number, which as we know in Python is an Integer. In this case we are stripping away the .5 value, leaving us with 6, which is our new Dividend.
- From here we simply do the same as before, using a Modulus equation of 6 % 2 = 0, leaving us with a remainder of 0 and the next value of our Binary number.
- binary_num_2: From here we simply repeat the same steps as with binary_num_3, except we divide it by 2 one more time.
- This leaves us with a value of 3, resulting in our Modulus equation being 3 % 2 = 1, leaving us with a remainder of 1 and the next value of our Binary number.
- binary_num_1: We repeat the same steps as with binary_num_2, and divide it by 2 once more.
- This leaves us with a value of 1, resulting in our Modulus equation being 1 % 2 = 1, leaving us with a remainder of 1 and the next value of our Binary number.
- Binary_num: We then put these remainder values next to each other, but in REVERSE order.
- If we print this, it results in a Tuple output of (1, 1, 0, 1).
- Int_result: While we can manually see the binary values within the Tuple, we can neaten this up by converting this Tuple to an Int, using the lambda equation.
- Once we print out the int_result, we get our final Binary number of 1101 which is the Decimal value of 13.
Note that the above will only work up to a Decimal number of 15, as this is the last Decimal number that contains 4 Binary values. From Decimal 16 on-wards, there are 5 Binary values (10000), therefore we need to add in an extra variable called binary_num_5:
import functools #import function tool for lambda equation to change Tuple to Int
decimal = 16
binary_num_5 = decimal % 2 # 16 % 2 = 0
binary_num_4 = int(decimal/2) % 2 # 16÷2 = 8. Therefore 8 % 2 = 0
binary_num_3 = int((decimal/2) /2) % 2 # Above, then 8÷2 = 4. Therefore 4 % 2 = 0
binary_num_2 = int(((decimal/2) /2) /2) % 2 # Above, then 4÷2 = 2. Therefore 2 % 2 = 0
binary_num_1 = int((((decimal/2) /2) /2) /2) % 2 # Above, then 2÷2 = 1. Therefore 1 % 2 = 1
binary_num = binary_num_1, binary_num_2, binary_num_3, binary_num_4, binary_num_5 # Reverse order for correct Binary
print(binary_num)
#>> (1, 0, 0, 0, 0) # Result in a Tuple
int_result = functools.reduce(lambda sub, ele: sub * 10 + ele, binary_num) # Change Tuple to Int
print(int_result)
#>> 10000
With this extra variable line added, everything else works as before and we get the final Binary number of 10000 which is the Decimal value of 16.
How to find a Binary Number using Python For Loop
An alternative way of using Python to calculate a Binary value from a Decimal, is to use a For Loop.
decimal = 13
result = ''
for x in range(8): # Range will allocate the amount of binary values
r = decimal % 2
decimal = decimal//2
result += str(r) #Convert to a String
result = result[::-1] # String Slicing using -1 to reverse order
print(result)
print(type(result))
#>> 00001101
#>> <class 'str'="">
Here again we enter the decimal number of 13 and set the range to 8, which will output an eight digit result.
We then use Python Floor Division to calculate the rest and convert it to a Python String, before reversing it using String Slicing.
When we run this code, we then get an output result of “00001101” which again is the Binary values that represent the Decimal number 13, even though it has multiple 0’s on the left. We can fix this by changing the range to 4, which will then only output 1101 instead or we can convert this output to an integer instead, as it is currently in a String format..
The other problem with it being in a String format is that it also cannot be used with any Python Arithmetic Operators unless it’s an Integer.To fix both these issues, lets convert this String to an Integer, by using the int() Function:
decimal = 13
result = ''
for x in range(8):
r = decimal % 2
decimal = decimal//2
result += str(r)
result = result[::-1]
print(result)
#>> 00001101
print(type(result))
#>> <class 'str'="">
int_result = int(result)
print(int(result))
#>> 1101
print(type(int_result))
#>> <class 'int'="">
By changing the Python String to an Integer not only allows us to use this output with any of the Python Arithmetic operators, but it also strips away any unnecessary 0’s on the left, giving us a much cleaner output result.
This means that we can now increase the range to any amount that we like (such as 50) and not have to worry about changing or it outputting 50 values.
Because it is not an Int, Python knows to strip away all unnecessary 0’s leaving only the required ones needed to represent the Binary number.
Let’s test this with a much larger Decimal number such as 27564:
decimal = 27564
result = ''
for x in range(50):
r = decimal % 2
decimal = decimal//2
result += str(r)
result = result[::-1]
print(result)
#>> 00000000000000000000000000000000000110101110101100
int_result = int(result)
print(int(result))
#>> 110101110101100 #Binary value of Decimal 27564
Using a While loop is definitely a superior way to calculate a Binary number from a Decimal number in Python, compared to using Modulus, but I wanted to show you both for educational purposes.
Conclusion
I hope you enjoyed this tutorial on how to calculate a Binary number from a decimal number using Python. This should give you the starting knowledge you need to easily implement it into you next Python code or project.
Binary in Python Summary
Here is a summary of what we learnt about Binary and how to calculate it using Python:
- The Binary System is a numerical system that consists of 0 and 1, which is used in state machines to represent ON or OFF.
- We count in Binary (also known as Base 2) in the same way we count in Decimal (also known as Base 10), as there are two base numbers in Binary and 10 base numbers in Decimal.
- When counting in either Binary or Decimal, we use columns to increment values 1 at a time until we reach the cap of the base value, in which case we reset to 0 and create a new column to the left.
- We can use Python to find a binary Number from a Decimal number using either the Modulus Operator or a For Loop.
Share the love
If you enjoyed this tutorial content and would like others to benefit from it as well, make sure to share it on your favorite Social Media platform, using the share buttons below.
Subscribe for News & Discount Offers
Subscribe right now to gain instant access to the latest news and tutorials while also being the first to know about, exclusive offers and discounts!