Skip to content

Instantly share code, notes, and snippets.

@joferkington
Last active December 7, 2015 18:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joferkington/4ce9dc5960bc205eadd0 to your computer and use it in GitHub Desktop.
Save joferkington/4ce9dc5960bc205eadd0 to your computer and use it in GitHub Desktop.
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