小编use*_*986的帖子

如何在二进制整数(python)中保持前导零?

我需要使用XOR计算十六进制串行字符串的校验和.对于我的(有限的)知识,这必须使用按位运算符^来执行.此外,数据必须转换为二进制整数形式.下面是我的基本代码 - 但它计算的校验和是1000831.它应该是01001110或47hex.我认为错误可能是由于错过了前导零.我试图添加前导零的所有格式都将二进制整数转换回字符串.我很感激任何建议.

    word = ('010900004f')

    #divide word into 5 separate bytes
    wd1 = word[0:2] 
    wd2 = word[2:4]
    wd3 = word[4:6]
    wd4 = word[6:8]
    wd5 = word[8:10]

    #this converts a hex string to a binary string
    wd1bs = bin(int(wd1, 16))[2:] 
    wd2bs = bin(int(wd2, 16))[2:]
    wd3bs = bin(int(wd3, 16))[2:]
    wd4bs = bin(int(wd4, 16))[2:]

    #this converts binary string to binary integer
    wd1i = int(wd1bs)
    wd2i = int(wd2bs)
    wd3i = int(wd3bs)
    wd4i = int(wd4bs)
    wd5i = int(wd5bs)

    #now that I have binary integers, …
Run Code Online (Sandbox Code Playgroud)

python python-2.7

2
推荐指数
1
解决办法
1838
查看次数

标签 统计

python ×1

python-2.7 ×1