I have an hexa string that I want to convert to a numpy array of int.
我有一个hexa字符串,我想转换为int的numpy数组。
I don't want to use for
loops because looping through numpy arrays is not advised.
我不想使用for循环,因为不建议循环使用numpy数组。
So I do the following :
所以我做了以下事情:
vector = np.fromstring( s.decode('hex'), dtype=np.uint8 )
vector = np.fromstring(s.decode('hex'),dtype = np.uint8)
If for example s = 'a312'
, s.decode('hex')
returns '\xa3\x12'
which is correct.
例如,如果s ='a312',则s.decode('hex')返回'\ xa3 \ x12',这是正确的。
But if s = 'a320'
, s.decode('hex')
returns '\xa3 '
which seems a little bit weird as first sight because I expect '\xa3\x20'
.
但是如果s ='a320',s.decode('hex')会返回'\ xa3',这看起来有点奇怪,因为我期待'\ xa3 \ x20'。
Can you help me ?
你能帮助我吗 ?
1 个解决方案
#1
1
The point is that a binary string in Pyhon is represented as its ASCII equivalent.
关键是Pyhon中的二进制字符串表示为其ASCII等价物。
The equivalent of '\x20'
is a space, as one can see in the ASCII table:
相当于'\ x20'是一个空格,如ASCII表中所示:
Hex Dec ASCII 20 32 (space)
If you write '\x20'
in the terminal, it will print a space:
如果在终端中写'\ x20',它将打印一个空格:
>>> '\x20'
' '
>>> 'a320'.decode('hex') == '\xa3\x20'
True
Note that this is only an aspect of representation: behind the curtains, the binary string contains the 0010 0000
binary value.
请注意,这只是表示的一个方面:在窗帘后面,二进制字符串包含0010 0000二进制值。
#1
1
The point is that a binary string in Pyhon is represented as its ASCII equivalent.
关键是Pyhon中的二进制字符串表示为其ASCII等价物。
The equivalent of '\x20'
is a space, as one can see in the ASCII table:
相当于'\ x20'是一个空格,如ASCII表中所示:
Hex Dec ASCII 20 32 (space)
If you write '\x20'
in the terminal, it will print a space:
如果在终端中写'\ x20',它将打印一个空格:
>>> '\x20'
' '
>>> 'a320'.decode('hex') == '\xa3\x20'
True
Note that this is only an aspect of representation: behind the curtains, the binary string contains the 0010 0000
binary value.
请注意,这只是表示的一个方面:在窗帘后面,二进制字符串包含0010 0000二进制值。