[英]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.