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 numberThe 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 decimalTo 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. For example: 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 numberThe 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. Example 1: Output: 11 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. Example 2: Another approach to convert a binary number to decimal in Python: Output: 11 Example 3: Another approach to convert binary to decimal is by using the built-in reduce() function from the functools module. Output: Enter a binary number: 100 Decimal equivalent of 100 is 4 Example 4: One more approach using the built-in int() function with a bit-wise shift operator: Output: Enter a binary number: 1000 Decimal equivalent of 1000 is 8. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India