Binary to decimal and vice-versa in python
Last Updated :
13 Apr, 2023
Write Python code for converting a decimal number to it’s binary equivalent and vice-versa.
Example:
From decimal to binary
Input : 8
Output : 1 0 0 0
From binary to decimal
Input : 100
Output : 4
Decimal to binary
Keep calling conversion function with n/2 till n > 1,
later perform n % 1 to get MSB of converted binary number.
Example :- 7
1). 7/2 = Quotient = 3(greater than 1), Remainder = 1.
2). 3/2 = Quotient = 1(not greater than 1), Remainder = 1.
3). 1%2 = Remainder = 1.
Therefore, answer is 111.
Python3
def binaryToDecimal(binary):
decimal, i = 0 , 0
while (binary ! = 0 ):
dec = binary % 10
decimal = decimal + dec * pow ( 2 , i)
binary = binary / / 10
i + = 1
print (decimal)
if __name__ = = '__main__' :
binaryToDecimal( 100 )
binaryToDecimal( 101 )
binaryToDecimal( 1001 )
|
Output
1 0 0 0
1 0 0 1 0
1 1 1
Time Complexity: O(log n)
Auxiliary Space: O(1)
Decimal to binary using bin():
Python3
def binaryToDecimal(n):
return int (n, 2 )
if __name__ = = '__main__' :
print (binaryToDecimal( '100' ))
print (binaryToDecimal( '101' ))
print (binaryToDecimal( '1001' ))
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Binary to decimal
Example -: 1011
1). Take modulo of given binary number with 10.
(1011 % 10 = 1)
2). Multiply rem with 2 raised to the power
it's position from right end.
(1 * 2^0)
Note that we start counting position with 0.
3). Add result with previously generated result.
decimal = decimal + (1 * 2^0)
4). Update binary number by dividing it by 10.
(1011 / 10 = 101)
5). Keep repeating upper steps till binary > 0.
Final Conversion -: (1 * 2^3) + (0 * 2^2) +
(1 * 2^1) + (1 * 2^0) = 11
Python3
n = 4
print ( '{0:b}' . format (n))
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Binary to decimal using int():
Python3
n = 4
binary = format (n, 'b' )
print (binary)
binary = '100'
decimal = int (binary, 2 )
print (decimal)
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Method: Using format specifier
Built-in format function:
Another approach for converting decimal to binary is to use the built-in format function. This approach involves formatting a decimal number as a binary string using the b format specifier. To convert a binary string back to its decimal equivalent, you can use the built-in int function with the base parameter set to 2. For example:
Python3
n = 4
binary = format (n, 'b' )
print (binary)
binary = '100'
decimal = int (binary, 2 )
print (decimal)
|
Time complexity: O(1), or constant time. The code performs a fixed number of operations regardless of the size of the input. Specifically, the code:
- Reads an integer from the user and assigns it to n.
- Converts n to a string in binary format and assigns the result to binary.
- Converts binary to an integer and assigns the result to decimal.
- Prints binary and decimal.
The time complexity of the code is determined by the time it takes to read an integer from the user, which is a fixed operation. Therefore, the time complexity of the code is O(1).
Auxiliary Space: O(1), or constant space. The code uses a fixed number of variables, regardless of the size of the input. Specifically, the code uses:
- The variable n to store a single integer.
- The variable binary to store a string representation of n in binary format.
- The variable decimal to store the decimal equivalent of binary.
Since the number of variables used is fixed and does not depend on the size of the input, the auxiliary Space of the code is O(1).
It’s worth noting that the specific time and space complexity of the conversion operations in this code may depend on the implementation of the built-in format and int functions. However, in general, these operations take O(1) time and space.
Similar Reads
Convert from any base to decimal and vice versa
Given a number and its base, convert it to decimal. The base of number can be anything such that all digits can be represented using 0 to 9 and A to Z. The value of A is 10, the value of B is 11 and so on. Write a function to convert the number to decimal. Examples: Input number is given as string a
15+ min read
Reading binary files in Python
Reading binary files means reading data that is stored in a binary format, which is not human-readable. Unlike text files, which store data as readable characters, binary files store data as raw bytes. Binary files store data as a sequence of bytes. Each byte can represent a wide range of values, fr
6 min read
Working with Binary Data in Python
Alright, lets get this out of the way! The basics are pretty standard: There are 8 bits in a byteBits either consist of a 0 or a 1A byte can be interpreted in different ways, like binary octal or hexadecimal Note: These are not character encodings, those come later. This is just a way to look at a s
5 min read
Convert Decimal to String in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting decimal to string. Converting Decimal to String str() method can be used to convert decimal to string in Python. Syntax: str(object, encoding=âut
1 min read
Convert Decimal to Other Bases in Python
Given a number in decimal number convert it into binary, octal and hexadecimal number. Here is function to convert decimal to binary, decimal to octal and decimal to hexadecimal. Examples: Input : 55 Output : 55 in Binary : 0b110111 55 in Octal : 0o67 55 in Hexadecimal : 0x37 Input : 282 Output : 28
2 min read
Decimal to binary number using recursion
Given a decimal number as input, we need to write a program to convert the given decimal number into an equivalent binary number. Examples : Input: d = 7 Output: 111Explanation: 20 + 21 + 22 = 1+2+4 = 7.Input: d = 10Output: 1010Explanation: 21 + 23 = 2+8 = 10. We previously discussed an iterative ap
4 min read
Python | Decimal to_integral_value() method
Decimal#to_integral_value() : to_integral_value() is a Decimal class method which returns the nearest integer without signaling Inexact or Rounded. Syntax: Decimal.to_integral_value() Parameter: Decimal values Return: the nearest integer without signaling Inexact or Rounded. Code #1 : Example for to
2 min read
numpy.binary_repr() in Python
numpy.binary_repr(number, width=None) function is used to represent binary form of the input number as a string. For negative numbers, if width is not given, a minus sign is added to the front. If width is given, the twoâs complement of the number is returned, with respect to that width. In a twoâs-
3 min read
Python | Pandas Series.str.isdecimal()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas isdecimal() is used to check whether all characters in a string are decimal. Th
2 min read
Create integer variable by assigning binary value in Python
Given a binary value and our task is to create integer variables and assign values in binary format. To assign value in binary format to a variable, we use the 0b prefix. It tells the compiler that the value (prefixed with 0b) is a binary value and assigns it to the variable. Input: Var = 0b1010Outp
2 min read