簡體   English   中英

如何在 Python 中將字符串轉換為十六進制字節?

[英]How to convert a string to hexadecimal bytes in Python?

我是 Python 的初學者。 我有一個字符串“TEST00000001”,它的長度為 12。我想將此字符串轉換為長度為 12 的十六進制字節,例如 b'\x54\x45\x53\x54\x30\x30\x30\x30 \x30\30\x30\x31'。

到目前為止,我成功地將我的字符串轉換為字節。 但是轉換后的字節長度是 24 而不是 12。

這是我到目前為止所做的:

sample_string = "TEST00000001"
output = ''.join(hex(ord(character_index))[2:] for character_index in sample_string)
hex_bytes = bytes(output, 'ascii')
print(hex_bytes)  # Output of this line is: b'544553543030303030303031'
print(len(hex_bytes))  # Length of my output is: 24

有人能幫我嗎?

無論架構如何,一個字節就是一個字節。 就我無法重現您的問題而言,我已經看到了:

>>> hex_string2 = "TEST00000001"
>>> byte_data = bytes(hex_string2, 'ascii')
>>> print(byte_data) #/ b'544553543030303030303031'
b'TEST00000001'
>>> print(len(byte_data)) #24
12

正如預期的那樣,上述工作。 可以嗎,在您的原始帖子中,您之前引用和設置了一個不同的變量(即變量輸出)?

byte_data = bytes(output, 'ascii')

因為如果你這樣做:

>>> hex_string2.encode("hex")
'544553543030303030303031'

現在,如果您想要一個兩位小數的列表,那么

>>> [this.encode("hex") for this in byte_data]
['54', '45', '53', '54', '30', '30', '30', '30', '30', '30', '30', '31']

這會是你想要得到的東西嗎?

要將字符串轉換為 Python 中的字節,請直接在字符串上使用bytes 不要在字符上調用ordhex

hex_string2 = "TEST00000001"
byte_data = bytes(hex_string2, 'ascii')
print(len(byte_data))
# 12

而 output 確實與b'\x54\x45\x53\x54\x30\x30\x30\x30\x30\x30\x30\x31'

byte_data == b'\x54\x45\x53\x54\x30\x30\x30\x30\x30\x30\x30\x31'
# True

相反,如果您的輸入是填充的十六進制表示的字節字符串,則需要對該表示進行解碼(例如使用binascii ):

import binascii
binascii.unhexlify(b'544553543030303030303031')
# b'TEST00000001'

codecs

import codecs
codecs.decode('544553543030303030303031', 'hex')
# b'TEST00000001'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM