Movatterモバイル変換


[0]ホーム

URL:


int 2 binary: What do you think?

Martin Blessm.bless at gmx.de
Mon Apr 23 09:31:01 EDT 2001


I needed to convert integers to binary representation and couldn'tfind a builtin function. So here's what I came up with. The idea is toreturn a string as short as possible and have positive numbers alwaysstart with a  "0".I wonder if there's a better way? And most probably there are lots of modules around offering  asolution, aren't they?Martin Blessb_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 rdef 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-listmailing list

[8]ページ先頭

©2009-2025 Movatter.jp