Python: Binary

 Hello and Welcome to Blog #8, Python: Binary. This post will introduce Binary in Python and and how to convert an integer to its binary form and back. 


First though, what is binary? Binary is just a base-2 number system that includes only zeros and ones. Normally, all numbers are made up of the numbers zero through nine, which is a base-10 system. With binary, all numbers are made up of combinations of 0 and 1. For example, number to binary form:

0 - 0

1- 1

2- 10

3 - 11

4 - 100

5 - 101

6 - 110


.....


Binary is stored in 'bits.' Bits are just the smallest type of binary data. Eight bits is equal to one 'byte.' One byte of data can store any number in binary form up to 255. Because each bit of data is equal to one digit in binary, and eight bits is one byte, that means one byte is eight binary digits. 255 is the last number, when converted to binary form, that only has eight digits; 256 needs 9 bits. 


Now, how to convert binary to integers and back in python. 


Converting an integer to binary:

To convert a number to binary from integer form, the built-in function, bin(), is used. The input goes between the parentheses, and the output is the binary form of the integer inputted:

bin(3)

Output will be '0b11'


bin(6)

Output will be '0b102'


The '0b' is just a way to show that it has been converted to binary. It is not part of the binary representation of the integer. The binary can be converted back, with or without the '0b.'

There are ways to convert some strings or other things to binary, but that will not be covered in this post. Now, converting the binary back to an integer. 


Converting Binary to Integer: 

To do this, the int function is once again used, but this time, you will need to define the base upon which you want to convert the input. To convert to an integer from binary, you will use base 2, as such:

int('0b10',2)

Output will be 2

This time, int has two parameters (whatever goes in between the parentheses. This will be explained in a later post about functions.) The first parameter is the input, or whatever you want to convert to an integer, and the second is the base on which you want to convert it, in this case, 2. If the base is not defined, then the function will always assume you want to convert to an integer on base 10, or with a normal 0-9 number system. When you define base 2, it knows it is binary, because binary is a base-2 number system, as it only has zeros and ones. 





Thank you for reading Python: Binary. Please leave any comments and questions in the comments section!






Comments