
In this example, we first have assigned the value ‘0b1010’ to the variable b_num. Print("Decimal equivalent of 0b101 is: ", result) Let’s take an example of how to convert a binary number to a decimal number using int() function.Įxample 2: # Python program to convert a binary number to decimal number. In the case of binary number system, the base is 2. The int() function takes two arguments: the first argument is the binary number, and the second argument is the base of the number system. We can also convert binary numbers to decimal numbers using the int() function.


Converting binary numbers to decimal numbers However, the binary representation of negative numbers is more complicated than that of positive numbers because it involves the use of two’s complement representation. Notice that the Python bin() function can also convert negative numbers to binary. We then have printed the returned results on the console.Īs you see in the output, the prefix 0b denotes that the number is in binary format. The bin() function has returned the binary equivalents “0b101”, “0b1010”, and “-0b101” that we have stored into variables result1, result2, and result3. Then, we have called the bin() function and passed the values of num1, num2, and num3, respectively. In this example, we have assigned three values 5, 10, and -5 to variables num1, num2, and num3, respectively.

Print("Binary equivalent of -5 is: ", result3) Print("Binary equivalent of 10 is: ", result2) Print("Binary equivalent of 5 is: ", result1) Example 1: # Python program to convert decimal numbers into binary equivalents.
