简体   繁体   English

如何在 Python 中将字符串转换为十六进制字节?

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

I am very beginner at Python.我是 Python 的初学者。 I have a string which is "TEST00000001" and its lenght is 12. I would like to convert this string to a hexadecimal byte with a 12 lenght like this b'\x54\x45\x53\x54\x30\x30\x30\x30\x30\30\x30\x31'.我有一个字符串“TEST00000001”,它的长度为 12。我想将此字符串转换为长度为 12 的十六进制字节,例如 b'\x54\x45\x53\x54\x30\x30\x30\x30 \x30\30\x30\x31'。

So far, I am successfully converting my string to bytes.到目前为止,我成功地将我的字符串转换为字节。 But length of converted bytes is 24 instead of 12.但是转换后的字节长度是 24 而不是 12。

Here is what I've done so far:这是我到目前为止所做的:

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

Can someone help me?有人能帮我吗?

A byte is a byte, no matter the architecture.无论架构如何,一个字节就是一个字节。 As far as I have been unable to reproduce your problems, I've seen this:就我无法重现您的问题而言,我已经看到了:

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

The above works, as expected.正如预期的那样,上述工作。 Can it be, that in your original post, you have a different variable that you are referencing and setting before (ie variable output)?可以吗,在您的原始帖子中,您之前引用和设置了一个不同的变量(即变量输出)?

byte_data = bytes(output, 'ascii')

Beacause if you do:因为如果你这样做:

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

Now if you would want a list of two digit decimals, then现在,如果您想要一个两位小数的列表,那么

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

Would this be something you are trying to get?这会是你想要得到的东西吗?

To convert a string into bytes in Python, use bytes directly on the string.要将字符串转换为 Python 中的字节,请直接在字符串上使用bytes Don't call ord or hex on the characters:不要在字符上调用ordhex

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

And the output is indeed the same as b'\x54\x45\x53\x54\x30\x30\x30\x30\x30\x30\x30\x31' :而 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

By contrast, if your input is a string of bytes in padded hexadecimal representation, you need to decode that representation (eg using binascii ):相反,如果您的输入是填充的十六进制表示的字节字符串,则需要对该表示进行解码(例如使用binascii ):

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

Or codecs :codecs

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

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

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