简体   繁体   English

Python bin() 和前导零

[英]Python bin() and leading zeros

As of Python 3 the leading zeros are excluded in a bin() conversion.从 Python 3 开始,在bin()转换中排除了前导零。

I am trying to manipulate a value and re-arrange the bits so I can decode an offset but after the conversion I am loosing the leading zeros from the value.我正在尝试操纵一个值并重新排列这些位,以便我可以解码一个偏移量,但在转换之后,我失去了该值的前导零。

Which would be the best way to do that without losing the leading zeros?在不丢失前导零的情况下,哪种方法是最好的方法?

Here is the code:这是代码:

bytefeed = 0x0229  # which becomes 0x2902

def decodebytes(bytefeed, negative = True):

    rearrangedbits = list()
    reversed_dat.extend([bytefeed[1], bytefeed[0]])
    reversed_datdec = int.from_bytes(reversed_dat, byteorder='big', signed=False)
    bitfield2 = list(bin(reversed_datdec)[2:])
    rearrangedbits += bitfield2[4:10]
    rearrangedbits += bitfield2[0:4]
    rearrangedbits += bitfield2[10:17]
    bitfieldec2 = int("".join(map(str, rearrangedbits)),2)
    decovaroffset = finaloffset - bitfieldec2

    print(bitfield2)
    return decovaroffset

the result of the bitfield2 is: bitfield2 的结果是:

['1', '0', '1', '0', '0', '1', '0', '0', '0', '0', '0', '0', '1', '0']

Should be:应该:

['0', '0', '1', '0', '1', '0', '0', '1', '0', '0', '0', '0', '0', '0', '1', '0']

zfill() is not an option here as the padding will affect the offset if the variables does not have leading zero. zfill()在这里不是一个选项,因为如果变量没有前导零,填充将影响偏移量。

seems that zfill() fixes the issue for the list as i had previously misunderstood the usage..似乎zfill()解决了列表的问题,因为我之前误解了用法..

so所以

bitfield2 = list(bin(reversed_datdec)[2:])

should be应该

bitfield2 = list(bin(reversed_datdec)[2:].zfill(16))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM