Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an Integer into 32bit Binary Python

Tags:

python

I am trying to make a program that converts a given integer(limited by the value 32 bit int can hold) into 32 bit binary number. For example 1 should return (000..31times)1. I have been searching the documents and everything but haven't been able to find some concrete way. I got it working where number of bits are according to the number size but in String. Can anybody tell a more efficient way to go about this?

like image 447
Pooja Gupta Avatar asked Mar 26 '17 02:03

Pooja Gupta


People also ask

How do you represent a 32-bit integer in Python?

The int data type in python simply the same as the signed integer. A signed integer is a 32-bit integer in the range of -(2^31) = -2147483648 to (2^31) – 1=2147483647 which contains positive or negative numbers. It is represented in two's complement notation.

How do you convert int to binary in Python?

Use Python bin to Convert Int to Binary The Python bin() function is short for binary and allows us to convert an integer to a binary string, which is prefixed by '0b' .

How do you write 32-bit in binary?

32 in binary is 100000. Unlike the decimal number system where we use the digits 0 to 9 to represent a number, in a binary system, we use only 2 digits that are 0 and 1 (bits). We have used 6 bits to represent 32 in binary.


2 Answers

'{:032b}'.format(n) where n is an integer. If the binary representation is greater than 32 digits it will expand as necessary:

>>> '{:032b}'.format(100)
'00000000000000000000000001100100'
>>> '{:032b}'.format(8589934591)
'111111111111111111111111111111111'
>>> '{:032b}'.format(8589934591 + 1)
'1000000000000000000000000000000000'    # N.B. this is 33 digits long
like image 199
mhawke Avatar answered Sep 28 '22 17:09

mhawke


You can just left or right shift integer and convert it to string for display if you need.

>>> 1<<1
2
>>> "{:032b}".format(2)
'00000000000000000000000000000010'
>>>

or if you just need a binary you can consider bin

>>> bin(4)
'0b100'
like image 35
Andy Wong Avatar answered Sep 28 '22 16:09

Andy Wong