简体   繁体   English

正确地从十六进制字符串转换为字节数组

[英]Correctly going from a Hexadecimal string to a byte array

I have a hexadecimal string made up from the following bytes: 我有一个由以下字节组成的十六进制字符串:

['0x17', '0x9', '0x5', '0x1f', '0x0', '0x4', '0x16', '0x0', '0x28', '0x53', '0x1c', '0x8', '0x12', '0x11', '0x40', '0xe', '0x54', '0x3b', '0x6', '0x1e', '0x45', '0x49', '0xa', '0x45', '0xe', '0x1c', '0x1f', '0x59', '0x41', '0x6', '0x4f', '0x59', '0xb', '0x16', '0x2', '0x44', '0x53', '0x1'] ['0x17','0x9','0x5','0x1f','0x0','0x4','0x16','0x0','0x28','0x53','0x1c','0x8',' 0x12','0x11','0x40','0xe','0x54','0x3b','0x6','0x1e','0x45','0x49','0xa','0x45','0xe' ,'0x1c','0x1f','0x59','0x41','0x6','0x4f','0x59','0xb','0x16','0x2','0x44','0x53','为0x1' ]

The hexadecimal string looks like: 十六进制字符串如下所示:

'17951f0416028531c8121140e543b61e4549a45e1c1f594164f59b16244531'

How can I retrieve the original byte array? 如何检索原始字节数组?

In python 3.x: 在python 3.x中:

bytes.fromhex('17951f0416028531c8121140e543b61e4549a45e1c1f594164f59b16244531')

returns 回报

b'\\x17\\x95\\x1f\\x04\\x16\\x02\\x851\\xc8\\x12\\x11@\\xe5C\\xb6\\x1eEI\\xa4^\\x1c\\x1fYAd\\xf5\\x9b\\x16$E1', B '\\ X17 \\ X95 \\ X1F \\ X04 \\ X16 \\ X02 \\ x851 \\ xc8 \\ X12 \\ X11 @ \\ xe5C \\ XB6 \\ x1eEI \\ XA4 ^ \\ X1C \\ x1fYAd \\ XF5 \\ x9b \\ X16 $ E1',

and in python 2.x: str('17951f0416028531c8121140e543b61e4549a45e1c1f594164f59b16244531').decode('hex') returns 并在python 2.x中: str('17951f0416028531c8121140e543b61e4549a45e1c1f594164f59b16244531').decode('hex')返回

b'\\x17\\x95\\x1f\\x04\\x16\\x02\\x851\\xc8\\x12\\x11@\\xe5C\\xb6\\x1eEI\\xa4^\\x1c\\x1fYAd\\xf5\\x9b\\x16$E1'. B '\\ X17 \\ X95 \\ X1F \\ X04 \\ X16 \\ X02 \\ x851 \\ xc8 \\ X12 \\ X11 @ \\ xe5C \\ XB6 \\ x1eEI \\ XA4 ^ \\ X1C \\ x1fYAd \\ XF5 \\ x9b \\ X16 $ E1'。

Both of which are completely wrong. 两者都是完全错误的。 The bytes.fromhex, and decode('hex') both read 2-bytes at a time, so '0x9' and '0x5' are read as '0x95'. 这些bytes.fromhex和decode('hex')一次都读取2个字节,因此'0x9'和'0x5'被读为'0x95'。 Is there anyway to fix this? 有没有什么办法解决这一问题?

Please note, I cannot control the generation of the original hexadecimal string. 请注意,我无法控制原始十六进制字符串的生成。 Cheers. 干杯。

In your string encoding, several pairs of bytes have been merged; 在您的字符串编码中,已合并了几对字节。 making sure that each byte is represented by two characters in your string, you'll get what you want: 确保每个字节由字符串中的两个字符表示,您将获得所需的内容:

In [6]: s
Out[6]: '1709051f0004160028531c081211400e543b061e45490a450e1c1f5941064f590b1602445301'

In [7]: bytes.fromhex(s)
Out[7]: b'\x17\t\x05\x1f\x00\x04\x16\x00(S\x1c\x08\x12\x11@\x0eT;\x06\x1eEI\nE\x0e\x1c\x1fYA\x06OY\x0b\x16\x02DS\x01'

Without knowing what sort of information the string represents, there is no a priori way of determining where the missing 0s should be added. 在不知道字符串代表什么样的信息的情况下,没有确定丢失的0应该添加到何处的先验方法。

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

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