
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Binary to Decimal and Vice Versa in Python
In this article, we will see how to convert Binary to Decimal and Decimal to Binary. Binary is the simplest kind of number system that uses only two digits of 0 and 1 (i.e. value of base 2). Since digital electronics have only these two states (either 0 or 1), so binary number is most preferred in modern computer engineer, networking and communication specialists, and other professionals.
Decimal number system has base 10 as it uses 10 digits from 0 to 9. In decimal number system, the successive positions to the left of the decimal point represent units, tens, hundreds, thousands, and so on.
Let's say the following is our Binary ?
1111
The output is the following Decimal ?
15
Let's say the following is our Decimal ?
20
The output is the following Binary ?
10100
Decimal To Binary Conversion in Python
In this example, we will convert Decimal to Binary ?
Example
s = 0 i = 1 myDec = 18 print("Decimal = ",myDec) # Loop through while myDec>0: rem = int(myDec%2) s = s+(i*rem) myDec = int(myDec/2) i = i*10 print ("The binary of the given number = ",s)
Output
Decimal = 18 The binary of the given number = 10010
Binary To Decimal Conversion in Python
In this example, we will convert Binary to Decimal ?
Example
s = 0 i = 1 myBin = "1101" print("Binary = ",myBin) n=len(myBin) res=0 for i in range(1,n+1): res = res+ int(myBin[i-1])*2**(n-i) print ("The decimal of the given binary = ",res)
Output
Binary = 1101 The decimal of the given binary = 13