Skip to content

Instantly share code, notes, and snippets.

@samuelreh
Created February 21, 2015 07:26
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 samuelreh/8a3b583fc5c10a18ffca to your computer and use it in GitHub Desktop.
Save samuelreh/8a3b583fc5c10a18ffca to your computer and use it in GitHub Desktop.
Bit Display
class Display(object):
HEIGHT = 8
WIDTH = 8
def __init__(self):
self.array = [0x00] * (self.width() / 8) * self.height()
def height(self):
""" Get the height of the display """
return self.HEIGHT
def width(self):
""" Get the width of the display """
return self.WIDTH
def address(self, x, y):
""" Get address of x, y """
return (x + y * self.width()) / 8
def setBit(self, x, y):
""" Set bit at x, y """
self.array[self.address(x,y)] |= self.mask(x)
return
def mask(self, x):
bit_index = x % 8
return (128 >> bit_index)
def test_bit(self, x, y):
mask = self.mask(x)
bits = self.array[self.address(x,y)]
return bool(bits & mask)
def toggle_bit(self, x, y):
self.array[self.address(x,y)] ^= self.mask(x)
return
def __repr__(self):
string = ""
for x in range(self.width()):
for y in range(self.height()):
if (self.test_bit(x, y)):
string += "+"
else:
string += " "
string += "\n"
return string
d = Display()
w = d.width()
for x in range(w):
d.setBit(x, x)
d.setBit(w - x, x)
d.setBit(x, 0)
d.setBit(w - 1, x)
d.setBit(x, w - 1)
d.setBit(0, x)
print d.test_bit(1,1)
d.toggle_bit(1,1)
print d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment