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
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.
1 Comment
slowkoni
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