简体   繁体   English

我想将十六进制字节数组转换为字符串格式的十六进制

[英]I want to convert a hexadecimal byte array to hexadecimal in string format

I want to convert byte format to string format.我想将字节格式转换为字符串格式。 The conversion target is as follows.转换目标如下。 \xb9S\xfc\x81\xe4\xa2\xb9\x92\x8d\xbb1\xfe\xb9\xa1&\x16\...... Convert to string format. \xb9S\xfc\x81\xe4\xa2\xb9\x92\x8d\xbb1\xfe\xb9\xa1&\x16\......转换成字符串格式。

For example, b'\xfc\x81\xe4\xa2\xb9\x92' #type:bytes -> "FC 81 E4 A2 B9 92" #type:str例如,b'\xfc\x81\xe4\xa2\xb9\x92' #type:bytes -> "FC 81 E4 A2 B9 92" #type:str

No matter how much I searched, I couldn't find the module by myself.无论我怎么搜索,我都无法自己找到该模块。 Any help would be appreciated.任何帮助,将不胜感激。

This is implemented in the standard lib这是在标准库中实现的

Starting with python 3.5, you got this:从 python 3.5 开始,你得到了这个:

val = b'AAAAA'
print(val.hex())
    
# prints '4141414141'

With python 3.8+, you can also specify a separator:使用 python 3.8+,您还可以指定一个分隔符:

val = b'AAAAA'
print(val.hex(' '))
    
# prints '41 41 41 41 41'

if you absolutely want them in uppercase, you can call upper() on the result.如果你绝对希望它们是大写的,你可以在结果上调用upper()

def format_bytes_as_hex(b: bytes) -> str:
    h = b.hex()
    return ' ' .join(f'{a}{b}'.upper() for a, b in zip(h[0::2], h[1::2]))


Test:
format_bytes_as_hex(b'\xfc\x81\xe4\xa2\xb9\x92')
'FC 81 E4 A2 B9 92'

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

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