Skip to content

Instantly share code, notes, and snippets.

@DeoLeung
Created December 26, 2017 06:21
Show Gist options
  • Save DeoLeung/2fc00b95eaef6f01bab351e496215f31 to your computer and use it in GitHub Desktop.
Save DeoLeung/2fc00b95eaef6f01bab351e496215f31 to your computer and use it in GitHub Desktop.
transform list of integers into bitmaps bytes and back
import numpy as np
ids = [1, 5, 7, 12]
bitmaps = np.zeros(max(ids) + 1, dtype=np.bool)
bitmaps[ids] = True
bitmaps = np.packbits(bitmaps).tostring()
print(bitmaps)
# b'E\x08'
# could be use as a binary field to be stored in database
origin_ids = np.where(
np.unpackbits(
np.frombuffer(bitmaps,
dtype=np.uint8)))[0].tolist()
print(origin_ids)
# [1, 5, 7, 12]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment