Python

Binary Numbers in Python

One technique of number representation is the binary number system. It is primarily used in digital computers or systems. Any device with only two possible operating states or conditions can represent the binary quantities which are represented by binary systems. A switch, for instance, simply has two states: on or off. To work with binary numbers in Python, we can use the basic approach and the inbuilt functions provided by Python, allowing us to convert the binary numbers into different number systems according to their requirements. For example, the binary values can be converted into decimal numbers and vice versa as well as into the octal number system. Normally, we can represent a binary system using the 0 or 1 digits. The binary number system’s radix, which we can also refer to as its base, is 2. In this tutorial, we will teach you the usage and working of binary numbers in Python.

Application of Binary Numbers

Computer programming languages use the binary number system which is helpful in digital encoding and is particularly valuable in computer technology. Binary numbers can also be used in Boolean algebra which is frequently used in programming.

Advantages and Disadvantages of the Binary Number System

The fundamental benefit of using a binary number system is that it provides an easy-to-represent base for electronic equipment. The binary numbers are very simple to use while coding, requires fewer calculations, and has lower computational error rates. Because there are so many more binary digits than there are corresponding decimal digits, binary numbers are difficult for humans to understand and write.

How to Convert Int to Binary in Python

This section helps us to understand the method of converting int to binary and also explains how binary strings are stored in computers. Then, we will learn four different Python conversion techniques for int to binary. The format() function, f-strings, bin() function, and Python implementation without the usage of any functions are a few examples that we will use for int to binary conversion.

First, understand the binary strings for integers:

The decimal system, which is the conventional integer system with which we are all familiar, contains ten different symbols since it is based on a base of ten. These symbols, which represent the 0 to 9 digits, allow us to create all of the conventional number combinations. Contrarily, binary strings only contain two digits to express various integers because they have a base of two.

Int to Binary Conversion

Let’s start by converting an integer into a binary using the bin() function.

Converting Int to Binary Using the Bin() Function

The bin()Python function which stands for “binary” enables us to turn an integer into a binary string that is prefixed by “0b”. We will also look at the conversion of an integer without a prefix in an upcoming section.

Code:

integer = 22

b = bin(integer)

print(b)

Output:

First, we create a variable and assign it an int value of 22. By passing this int variable in the bin(), the function returns a binary string “10110” with the 0b prefix. We can also verify the type of output value with the help of the type() method.

Code:

integer = 22

b = bin(integer)

print(type(b))

Output:

Let’s try using bin() to convert a negative integer to a binary string:

Code:

neg = -20

b = bin(neg)

print(b)

Output:

We can see that our string also contains “-“ which indicates that the returned binary string is a negative value.

Converting Int to Binary Using the String Formatting

String formatting can be used to create a binary string from a Python integer without the “0b” prefix. We can define the various format types to send in the values using Python’s string formatting functionality. In this instance, we input the format code “{0:b}” which enables us to convert int into binary.

Let’s see how we can use the string formatting to pass a few integer values, both positive and negative, for int to binary conversion.

Code:

pos = 45

neg = -45

pos_to_bin = '{0:b}'.format(pos)

neg_to_bin = '{0:b}'.format(neg)

print(f'{pos_to_bin =}')

print(f'{neg_to_bin =}')

Output:

As can be seen, the function returned the binary string without the “0b” prefix .

Converting Int to Binary Using f-Strings

String formatting can be made a little more understandable with the help of Python f-strings. They also enable us to format our strings in a manner that is similar to conventional string formatting. The f-strings in Python are strings that are formed by prefixing the string with either an “f” or “F”. Let’s look at how Python f-strings can be used to transform an integer into a binary string.

Code:

pos = 14

neg = -14

pos_binary = f'{pos:b}'

neg_binary = f'{neg:b}'

print(f'{pos_binary=}')

print(f'{neg_binary=}')

Output:

Here, we can observe that the function successfully converted the given values to binary strings. Python f-strings might not function in all Python versions, but they are simple to use and understand.

You’ll discover how to transform an int into a binary string using the Python format() method in the following section.

Converting Int to Binary Using the Format() Method

Using the built-in format() method is another way of converting a Python int to a binary string. Value/int and a format specification can be inputted to the format() method as arguments. Since we wish to get a binary string as a result, we pass an integer and a format is specified as “b”.

Code:

pos = 42

neg = -42

pos_binary = format(pos, 'b')

neg_binary = format(neg, 'b')

print(pos_binary)

print(neg_binary)

Output:

This way to convert Python int to string is highly readable and simple. By specifying a type, the method understands that we are changing one value into another.

Converting Int to Binary Using Plain Python

Now, you’ll see how to perform the Python integer to string conversion. A custom function is created to accomplish this, but you’ll be able to comprehend how the conversion functions. Though you won’t need to do this in practice, if you work as a Python developer, you should be familiar with this int to binary conversion technique.

Code:

def IntToBinary(int):

binary_str = ''

while(int > 0):

digit = int % 2

binary_str += str(digit)

int = int // 2

binary_str = binary_str[::-1]

return binary_str

print(IntToBinary(18))

Output:

The drawback of using this function is that it only works for the positive int values.

We have seen how int can be converted into binary in Python. We can also convert the strings into binary values using multiple functions.

String to Binary Conversion

Here, we will use the join(), ord(), and format() methods to convert a string to binary. The characters in the provided string are converted into binary using their respective ASCII values.

Let’s look at the list of the functions which will be used in the following code for the string to binary conversion

join(): To create a single entity, it takes all the items/components and joins them. This function joins every character (including white spaces) of the specified string into a single entity.

Ord(): This method converts a character into the associated UNICODE value.

format(): Through point data format, it allows you to concatenate the fragments of a string at specified intervals.

Now, we convert the given string to binary using these functions:

Code:

string = "we love python"

print("specified string = ", string)

binary = ''.join(format(ord(x), '08b') for x in string)

print("binary = ",binary)

Output:

First, the string “we love Python” is declared to be converted into binary. Then, we printed the string to display it in the output. The format() method was then used, using the ord() and “08b” parameters to convert each character of the string into binary using a for a loop. Finally, we printed the binary value that is stored in the “binary” variable.

Conclusion

In this tutorial, we first explored the introduction of the binary number system. We discussed some applications of binary numbers along with their advantages and disadvantages. Then, we discussed how to convert an int to binary using Python. We explained how to accomplish this in a variety of ways including using the format() function, f-strings, the Python bin() function, and using plain Python. We also implemented an example to show how the strings can be converted into binary.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.