Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Writing an arbitrary, pre-existing numpy array to a hetergenous binary format
import numpy as np
# Our input data...
x = np.random.randint(0, 3200, (1000,1000))
# We're replacing something like
# struct.pack(">"+"hB"*x.size)
# Note that that's a 2-byte signed int followed by 1-byte unsigned
# We'll need to create the output 1D array and assign manually:
out = np.zeros(x.size // 2, dtype='>i2,>u1')
out['f0'], out['f1'] = x.flat[::2], x.flat[1::2]
# or more generally:
# out[out.dtype.names[0]], out[out.dtype.names[1]] = x[::2], x[1::2]
result = out.tostring()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.