[英]How to get the raw bytes from a hex string in python
I have the following problem in python我在 python 中有以下问题
I have the value 0x402de4a in hex and would like to convert it to bytes so I use.to_bytes(3, 'little') which gives me b'J\2d@'
if I print it.我有十六进制值 0x402de4a 并且想将其转换为字节,所以我使用 .to_bytes(3, 'little') 如果我打印它会给我
b'J\2d@'
。 I am aware that this is just a representation of the bytes but I need to turn a string later for the output which would give me J\2d@
if I use str() nut I need it to be \x4a\x2d\x40
how can I convert the byte object to string so I can get the raw binary data as a string我知道这只是字节的表示,但我需要稍后为 output 转一个字符串,如果我使用 str() 螺母,这会给我
J\2d@
我需要它是\x4a\x2d\x40
如何我可以将字节 object 转换为字符串,以便我可以将原始二进制数据作为字符串获取
my code is as follows我的代码如下
addr = 0x402d4a
addr = int(addr,16)
addr = str(addr.to_bytes(3,'little'))
print(addr)
and my expected output is \x4a\x2d\x40
而我预期的 output 是
\x4a\x2d\x40
Thanks in advance提前致谢
There is no direct way to get \x4a\x2d
and so forth from a string.没有直接的方法可以从字符串中获取
\x4a\x2d
等。 Or bytes, for this matter.或字节,就此而言。
What you should do:你应该做什么:
"\\x"
prefix"\\x"
前缀的十六进制值join()
them join()
他们2 & 3 can nicely be folded into one generator comprehension, eg: 2 & 3 可以很好地折叠成一个生成器理解,例如:
rslt = "".join(
f"\\x{b:02x}" for b in value_as_bytes
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.