How to convert binary to decimal numbers in python?
The binary is a base-2 number system, which means it uses only two digits - 0 and 1. On the other hand, decimal is a base-10 number system, meaning it uses ten digits - 0 to 9.
To convert a binary number to decimal in Python, we need to follow a few simple steps:
Step 1: Obtain the binary number
The first step is to get the binary number that we want to convert. We can represent binary numbers in Python using the prefix '0b' followed by the binary digits. For example, the binary number 1011 can be represented in Python as '0b1011'.
Step 2: Convert the binary number to decimal
To convert the binary number to decimal, we need to multiply each binary digit with its corresponding power of 2 and then add up the results. The rightmost digit has a power of 2^0, the next digit has a power of 2^1, the next digit has a power of 2^2, etc.
If we want to convert the binary number '0b1011' to decimal, we would follow these steps:
Adding up these results gives us a total of 1 + 2 + 0 + 8 = 11. Therefore, the binary number '0b1011' is equivalent to the decimal number 11.
Step 3: Output the decimal number
The final step is to output the decimal number that we obtained in step 2. We can do this using the built-in Python function int(), which converts a string or number to an integer. We simply pass the binary number as a string to the int() function, along with argument 2 to indicate that the number is in base-2 (binary) format.
This code snippet first assigns the binary number '0b1011' to the variable binary_number. After that, it converts the binary number to decimal using the int() function and assigns the result to the variable decimal_number. Finally, it prints the decimal number using the print() function.
Another approach to convert a binary number to decimal in Python:
Another approach to convert binary to decimal is by using the built-in reduce() function from the functools module.
Enter a binary number: 100 Decimal equivalent of 100 is 4
One more approach using the built-in int() function with a bit-wise shift operator:
Enter a binary number: 1000 Decimal equivalent of 1000 is 8.
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week