From 4d370842c45713f9e71a665a89918c43d8d3b035 Mon Sep 17 00:00:00 2001 From: Wenru Dong Date: Tue, 8 Jan 2019 20:44:21 +0000 Subject: [PATCH] bitmap in python --- python/45_bitmap/bitmap.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 python/45_bitmap/bitmap.py diff --git a/python/45_bitmap/bitmap.py b/python/45_bitmap/bitmap.py new file mode 100644 index 0000000..1022b74 --- /dev/null +++ b/python/45_bitmap/bitmap.py @@ -0,0 +1,30 @@ +""" + Author: Wenru Dong +""" + +from typing import Optional + +class Bitmap: + def __init__(self, num_bits: int): + self._num_bits = num_bits + self._bytes = bytearray(num_bits // 8 + 1) + + def setbit(self, k: int) -> None: + if k > self._num_bits or k < 1: return + self._bytes[k // 8] |= (1 << k % 8) + + def getbit(self, k: int) -> Optional[bool]: + if k > self._num_bits or k < 1: return + return self._bytes[k // 8] & (1 << k % 8) != 0 + + +if __name__ == "__main__": + bitmap = Bitmap(10) + bitmap.setbit(1) + bitmap.setbit(3) + bitmap.setbit(6) + bitmap.setbit(7) + bitmap.setbit(8) + + for i in range(1, 11): + print(bitmap.getbit(i)) \ No newline at end of file