- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- 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

- Related Articles
- C++ Program to Convert Binary Number to Decimal and vice-versa
- How to Convert Decimal Number to Binary/Octal/Hex Number or Vice Versa in Excel?
- Convert from any base to decimal and vice versa in C++
- C++ Program to convert Octal Number to Decimal and vice-versa
- C++ Program to Convert Binary Number to Octal and vice-versa
- Convert string to DateTime and vice-versa in Python
- Adding Tuple to List and vice versa in Python
- Python – Test String in Character List and vice-versa
- Converting string to number and vice-versa in C++
- Converting Strings to Numbers and Vice Versa in Java.
- C Program for LowerCase to UpperCase and vice-versa
- How to get ArrayList to ArrayList and vice versa in java?
- How to convert String to StringBuilder and vice versa Java?
- How to convert an integer to hexadecimal and vice versa in C#?
- How to convert an array to Set and vice versa in Java?