简体   繁体   English

如何将十六进制作为字符串放入字节?

[英]How could I put hex as string into byte?

I am trying manually build a byte from hexadecimal:我正在尝试从十六进制手动构建一个字节:

>>> '\x74'
't'
>>> hex(116)
'0x74'
>>> hex(116)[1:]
'x74'
>>> '\\' + hex(116)[1:]
'\\x74'
>>> 

Is it possible to create exactly \\x74 as byte?是否可以将\\x74精确地创建为字节?

Without using magic with chr() .不使用chr()魔法。

>>> chr(int(hex(116), 16))
't

You can also do something like '74'.decode('hex') .您还可以执行类似'74'.decode('hex')

Output:输出:

>>> '74'.decode('hex')
't'

Perhaps you are looking forstruct.pack :也许您正在寻找struct.pack

In [210]: import struct

In [211]: struct.pack('1B', 0x74)
Out[211]: 't'

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

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