3

Is there a direct way instead of the following?

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

3 Answers 3

9

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)
6

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).

2
  • It was just for a hash value - for which I guess there's no advantage (actually a bit slower) - but for buffers this is much better. Mar 11, 2015 at 19:53
  • Yeah, now I see the proper data type. Mar 11, 2015 at 20:10
1

I'm not sure about the data type.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.