0

I have an hexa string that I want to convert to a numpy array of int.

I don't want to use for loops because looping through numpy arrays is not advised.

So I do the following :

vector = np.fromstring( s.decode('hex'), dtype=np.uint8 )

If for example s = 'a312', s.decode('hex') returns '\xa3\x12' which is correct.

But if s = 'a320', s.decode('hex') returns '\xa3 ' which seems a little bit weird as first sight because I expect '\xa3\x20'.

Can you help me ?

SebMa
  • 4,037
  • 29
  • 39

1 Answers1

1

The point is that a binary string in Pyhon is represented as its ASCII equivalent.

The equivalent of '\x20' is a space, as one can see in the ASCII table:

Hex  Dec  ASCII
 20   32    (space)

If you write '\x20' in the terminal, it will print a space:

>>> '\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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Ok I see. I guess maybe `decode`is not what I need. How can I get `'\xa3\x20'` from a `s = 'a320'` ? – SebMa Jun 29 '17 at 17:17
  • @SebMa: did you read the answer carefully? You get `\xa3\x20`. It is all a matter of how a **string is represented**. – Willem Van Onsem Jun 29 '17 at 17:19
  • You are right, it's the end of the day, I'm starting to get tired. `decode()` does what I want in the end and I get the expected integer value : `np.fromstring( '\xa3 ', dtype=np.uint8 )[1]` – SebMa Jun 29 '17 at 17:22
  • With python3, `s.decode('hex')` does not work : `AttributeError: 'str' object has no attribute 'decode'`, how can I make the code work in both python2 and python3 ? – SebMa Jun 30 '17 at 13:55
  • @SebMa: In Python-3.x there is indeed no decode. You can use [`bytes`](https://stackoverflow.com/a/3284069/67579) for that. Besides that Python-2.x and Python-3.x are actually two different languages. Making a program that works on both is in theory possible, but very hard (since for instance `map`, `zip`, etc. all have different behavior). – Willem Van Onsem Jun 30 '17 at 13:56