在python中处理二进制文字

时间:2012-12-09 22:26:26

标签: python binary hex

我正在尝试将代码从php转换为python。我有一个二进制文字列表 -

['0b0', '0b0', '0b0', '0b0', '0b0', '0b0', '0b100', '0b1001100']

连接时等于0000000000000000000000000000000000000000000000000000010001001100

int("0000000000000000000000000000000000000000000000000000010001001100",2)

给出1100

如何从列表中进行此操作。无法连接二进制文字。

4 个答案:

答案 0 :(得分:1)

>>> l = ['0b0', '0b0', '0b0', '0b0', '0b0', '0b0', '0b100', '0b1001100']
>>> int("".join("%02x" % int(x,0) for x in l), 16)
1100

Python将0b0101理解为二进制文字,因此我使用int('0b0101', 0)将每个部分转换为int。然后我以一种方便的格式(十六进制的两位数)格式化它,连接它们,并将它们解释为十六进制整数。

答案 1 :(得分:1)

您需要使用zfill方法用正确数量的零填充元素

li = ['0b0', '0b0', '0b0', '0b0', '0b0', '0b0', '0b100', '0b1001100']
zero_padded = [x[2:].zfill(8) for x in li]
print ''.join(zero_padded)

输出

0000000000000000000000000000000000000000000000000000010001001100

答案 2 :(得分:0)

只需剥离0b

binary = ''.join(x[2:] for x in yourlist)
print binary
print int(binary, 2)

答案 3 :(得分:0)

这对你来说是否丑陋:

int(''.join([i for sl in [s[2:].zfill(8) for s in l] for i in sl]),2)

(似乎有效。)

也许这更具可读性:

l = ['0b0', '0b0', '0b0', '0b0', '0b0', '0b0', '0b100', '0b1001100']
n = 0
for s in l:
    n = n*256 + int(s,2)
print n