python:求整数的二进制表示

求解方法:

1、整数求余

2、重复进行,整数除2再求余,直到除数为0

3、拼接余数

4、反转字符串

def int2two(intNo):
    twoStr=''
    if intNo == 0:
        twoStr = '0'
    while intNo != 0:
        intMod = intNo % 2
        intNo = intNo//2
        twoStr = twoStr + str(intMod)

    return '0b%08d' %int(twoStr[::-1])

if __name__ == '__main__':
    print(int2two(2796202))
    print(bin(2796202))

 

运行结果:
C:\Users\suneee\AppData\Local\Programs\Python\Python36\python.exe E:/wangjz/PyWorkSpace/LearnPython/int2bin.py
0b1010101010101010101010
0b1010101010101010101010

Process finished with exit code 0

posted on 2018-08-01 15:30  一個未来  阅读(4486)  评论(0编辑  收藏  举报

导航