繁体   English   中英

python 中的二进制字符串数据到十六进制

[英]Binary String data to Hexadecimal in python

binaryValue= '000000000000000011110011'

我想分隔 8 个字符并将 8 位转换为十六进制格式,因为上面的值为'0x000x000xf3'

我希望通过 python 将此值打印为'\x00\x00\xf3' 请让我知道如何使用 python 来实现这一点。 请让我知道如果在每个 binaryValue 字符串末尾都有'\n'会发生什么。 如何实现这一点。

您可以执行以下操作:

inputStr = '000000000000000011110011'
n = 8
listOfBytes = [inputStr[i:i+n] for i in range(0, len(inputStr), n)]
for i in listOfBytes: 
    print(hex(int(i, 2)))

输出_:

0x0 0x0 0xf3

那么你可以这样做:

b = '000000000000000011110011'
h = '\\' + '\\'.join('x' + hex(int(b[i:i + 8], 2)).split('x')[1].zfill(2) for i in range(0, len(b), 8))
print(h) # This will print \x00\x00\xf3

将其分解为更长的循环以使其更具可读性:

b = '000000000000000011110011'
h = ''
for i in range(0, len(b), 8): # Same as you did
    temp = hex(int(b[i:i + 8], 2)) # Same as you did
    temp = temp.split('x')[1] # to get the last part after x
    temp = temp.zfill(2) # add leading zeros if needed
    h += '\\x' + temp # adding the \x back
print(h) # This will print \x00\x00\xf3

我猜您必须将其用作 unicode 和/或将其转换为其他东西? 如果是这样,请在此处查看答案: Python: unescape "\xXX"

我想出的正确答案是:

binaryString = '000000000000000011110011'
hexString = ''
for i in range(0, len(binaryString), 8):
    if len(hex(int(binaryString[i:i + 8], 2))) == 3:
        tempString = hex(int(binaryString[i:i + 8], 2)).replace("0x", "\\x")
        hexString += "0" + tempString
    else:
        hexString += hex(int(binaryString[i:i + 8], 2)).replace("0x", "\\x")

print(hexString)

暂无
暂无

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

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