3

Is there a direct way instead of the following?

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

3 Answers 3

10

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)
Sign up to request clarification or add additional context in comments.

Comments

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 Comments

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.
Yeah, now I see the proper data type.
1

I'm not sure about the data type.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.