user3467349
user3467349

Reputation: 3191

Convert python byte string to numpy int?

Is there a direct way instead of the following?

np.uint32(int.from_bytes(b'\xa3\x8eq\xb5', 'big'))

Upvotes: 3

Views: 16635

Answers (3)

Nathan
Nathan

Reputation: 10306

Using np.fromstring for this is deprecated now. Use np.frombuffer instead. You can also pass in a normal numpy dtype:

import numpy as np
np.frombuffer(b'\xa3\x8eq\xb5', dtype=np.uint32)

Upvotes: 10

mgilson
mgilson

Reputation: 309929

The trick is to get the right datatype. To read big endian uint32 from a string the datatype (as a string) is '>u4'.

>>> np.fromstring(b'\xa3\x8eq\xb5', dtype='>u4')
array([2744021429], dtype=uint32)

This gives you an array back, but getting a scalar from there is a pretty trivial matter. More importantly, it allows you to read a large number of these objects in one go (which you can't do with your int.from_bytes trick).

Upvotes: 6

Eli Korvigo
Eli Korvigo

Reputation: 10503

I'm not sure about the data type.

np.fromstring(b'\xa3\x8eq\xb5', dtype='<i')

Upvotes: 1

Related Questions