![](/img/trans.png)
[英]Python: How to convert a string containing hex bytes to a hex string
[英]How to convert hex string starting with 0 to bytes with certain lenght in python
我想轉換:
'01' -> \x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
'0001' -> \x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
我試過這樣的事情:
int(data,16).to_bytes(16, byteorder='little')
但是當字符串以'00'開頭時,這不起作用。 還有其他方法嗎?
您可以使用bytes.fromhex
和bytes.ljust
:
>>> bytes.fromhex('01').ljust(16, b'\0')
b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> bytes.fromhex('0001').ljust(16, b'\0')
b'\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.