Skip to content

Commit

Permalink
bitmap in python
Browse files Browse the repository at this point in the history
  • Loading branch information
jerryderry committed Jan 8, 2019
1 parent b974998 commit 4d37084
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions python/45_bitmap/bitmap.py
Original file line number Diff line number Diff line change
@@ -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))

0 comments on commit 4d37084

Please sign in to comment.