简体   繁体   English

Python 十六进制字符串到带反斜杠的十六进制字符串

[英]Python Hex-String to Hex-String with Backslash

I'm really confused, with Byte-Strings in Python.我真的很困惑,Python 中的字节字符串。

I need to compare two Byte-Strings, so they should be converted the same (?)我需要比较两个字节字符串,所以它们应该被转换成相同的(?)

I have a String of Hex-Values:我有一串十六进制值:

52fab71f49a01ef92e793b41c13c5458080679919c7e5888f195935bd50c1bb8 52fab71f49a01ef92e793b41c13c5458080679919c7e5888f195935bd50c1bb8

If I convert this to a Byte-String with bytes.fromHex('52fab...') I get:如果我使用bytes.fromHex('52fab...')将其转换为字节字符串,我会得到:

b'R\xfa\xb7\x1fI\xa0\x1e\xf9.y;A\xc1<TX\x08\x06y\x91\x9c~X\x88\xf1\x95\x93[\xd5\x0c\x1b\xb8' b'R\xfa\xb7\x1fI\xa0\x1e\xf9.y;A\xc1<TX\x08\x06y\x91\x9c~X\x88\xf1\x95\x93[\xd5\x0c\x1b\xb8 '

But I want the 'R' at the beginning as '0x52' .但我希望开头的'R''0x52' How can I achieve this?我怎样才能做到这一点?
Why do I get 'R' instead of '0x52' ?为什么我得到'R'而不是'0x52' As Example, for the 2nd Byte, I get '0xfa' for 'fa' .例如,对于第 2 个字节,我得到 ' 'fa' '0xfa' ' 。

Same Problem with the other Ascii "Letter" like 'y', ';', 'A'... 'y'、';'、'A' 等其他 Ascii“字母”也存在同样的问题......

I hope this is not too confusing - I haven't found a appropriate solution after a long research.我希望这不会太令人困惑——经过长时间的研究,我还没有找到合适的解决方案。

Greetings问候

Daniel丹尼尔

You can't.你不能。

If you're using the standard bytes type, that's what its string representation is going to look like: it will represent all ASCII characters as themselves.如果您使用标准bytes类型,这就是它的字符串表示形式:它将所有 ASCII 字符表示为它们本身。 For example, b'\x42' is the ASCII 'R' character, so it'll be printed as itself.例如, b'\x42'是 ASCII 'R'字符,所以它会被打印为它本身。

Of course, you can create your own function to get the output you want, like:当然,您可以创建自己的 function 以获得您想要的 output,例如:

def print_me(thing: bytes):
    print(''.join(
        f'\\x{byte:02x}'
        for byte in thing
    ))

>>> print_me(bytes.fromhex("52fab71f49a01ef92e793b41c13c5458080679919c7e5888f195935bd50c1bb8"))
\x52\xfa\xb7\x1f\x49\xa0\x1e\xf9\x2e\x79\x3b\x41\xc1\x3c\x54\x58\x08\x06\x79\x91\x9c\x7e\x58\x88\xf1\x95\x93\x5b\xd5\x0c\x1b\xb8

but the underlying data stored in your bytes object will still be the same, no matter how you represent it.但是存储在您的bytes object 中的基础数据仍然是相同的,无论您如何表示它。

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

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