Get binary presentation of a number

# 32 bits integer max
max = 0x7FFFFFFF
# 32 bits interger min
min = 0x80000000
mask = 0xFFFFFFFF
def bin32(a):
    mask = 0xFFFFFFFF
    a &= mask
    res = ''
    i = 0
    while a != 0 or i < 32:
        res = str(a & 1) + res
        a >>= 1
        i += 1
    return res

def bin64(a):
    mask = 0xFFFFFFFFFFFFFFFF
    a &= mask
    res = ''
    i = 0
    while a != 0 or i < 64:
        res = str(a & 1) + res
        a >>= 1
        i += 1
    return res

bin32(2)
bin32(~2)
bin32(~2+1)
bin32(-2) # -2 = ~2 + 1
bin32(1)
bin32(-1)
# or simply
def bin32(a):
    mask = 0xFFFFFFFF
    a = bin(a&mask)[2:]
    return a

def bin64(a):
    mask = 0xFFFFFFFFFFFFFFFF
    a = bin(a&mask)[2:]
    return a

你可能感兴趣的:(Get binary presentation of a number)