2

If I have a 16-byte string, how can I cast it to an array of 2 uint64 in numpy? (specifying either little-endian or big-endian)

1 Answer 1

3

IIUC, you can use np.fromstring:

>>> n = range(16)
>>> s = ''.join(map(chr, n))
>>> np.fromstring(s, dtype=np.uint64)
array([506097522914230528, 1084818905618843912], dtype=uint64)
>>> sum((256**i)*x for i,x in enumerate(n[:8]))
506097522914230528L
>>> sum((256**i)*x for i,x in enumerate(n[8:]))
1084818905618843912L

although you'll have to flip endianness yourself. And it's more of a conversion than a cast, although people often use cast pretty loosely.

Sign up to request clarification or add additional context in comments.

1 Comment

At time of writing this, np.fromstring() is deprecated in favor of np.frombuffer() but otherwise the usage is exactly the same as DSM's answer above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.