我在 Python 中有这部分代码:
for line in response.body.split("\n"):
if line != "":
opg = int(line.split(" ")[2])
opc = int(line.split(" ")[3])
value = line.split(" ")[5]
if command == 'IDENTIFY':
if opg==opcodegroupr and opc==opcoder:
print line
ret['success'] = "IDENTIFY: The value is %s " % (value)
self.write(tornado.escape.json_encode(ret))
self.finish()
变量'line'是这样制作的:
1363005087 2459546910990453036 151 88 4 0x15000000
每个字段都是一个整数,但不是最后一个字段。最后一个字段是一个十六进制数。
我会采用这个十六进制数,然后按字节拆分字节。例如我会那样 0x15000000 被拆分为 15 00 00 00。
我该怎么办?我尝试使用 value.encode("hex") 但不能正常工作...值是一个字符串?我不知道如何考虑这个变量..
最佳答案
如果十六进制值已经是文本,则不需要再进行转换:
>>> text = "0x15000000"
>>> text = text[2:] # remove literal type prefix
>>> text = text.zfill(len(text) + len(text) % 2) # pad with zeros for even digits
>>> ' '.join(text[i: i+2] for i in range(0, len(text), 2)) # split into 2-digit chunks
'15 00 00 00'
(根据 @tobias-k 关于零填充的建议编辑)
关于python - 在 Python 中将十六进制字符串拆分为 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15338758/