int 2 binary: What do you think?
Martin Bless
m.bless at gmx.de
Mon Apr 23 09:31:01 EDT 2001
I needed to convert integers to binary representation and couldn't
find a builtin function. So here's what I came up with. The idea is to
return a string as short as possible and have positive numbers always
start with a "0".
I wonder if there's a better way?
And most probably there are lots of modules around offering a
solution, aren't they?
Martin Bless
b_nibbles = [
'0000', '0001', '0010', '0011',
'0100', '0101', '0110', '0111',
'1000', '1001', '1010', '1011',
'1100', '1101', '1110', '1111']
# Another way to create b_nibbles:
# b_nibbles = [a+b+c+d for a in ['0','1'] for b in ['0','1'] \
# for c in ['0','1'] for d in ['0','1']]
def i2bstr(arg):
"""Return integer as binary string."""
import sys
isPositive = (arg >= 0)
maskHighNibble = sys.maxint >> 3
r = ''
while 1:
r = b_nibbles[arg & 0xF] + r
arg = (arg >> 4) & maskHighNibble
if not arg:
if isPositive and r[0] == '1':
return '0000' + r
else:
return r
def test_i2bstr():
"""Demonstration of i2bstr()."""
import sys
integers = [0,1,15,16,255,256,32767,32768,
sys.maxint,-sys.maxint-1,-256,-32768, -1]
for i in integers:
print "%12d %s" % (i, i2bstr(i))
## Output:
## 0 0000
## 1 0001
## 15 00001111
## 16 00010000
## 255 000011111111
## 256 000100000000
## 32767 0111111111111111
## 32768 00001000000000000000
## 2147483647 01111111111111111111111111111111
## -2147483648 10000000000000000000000000000000
## -256 11111111111111111111111100000000
## -32768 11111111111111111000000000000000
## -1 11111111111111111111111111111111
More information about the Python-list
mailing list