Skip to content

Instantly share code, notes, and snippets.

@zwegner
Created January 13, 2020 02:30
Show Gist options
  • Save zwegner/6841688fa897aef64a11016967c36f2d to your computer and use it in GitHub Desktop.
Save zwegner/6841688fa897aef64a11016967c36f2d to your computer and use it in GitHub Desktop.
Ternary logic multiplication (0, 1, unknown)
N_BITS = 8
MASK = (1 << N_BITS) - 1
class Ternary:
def __init__(self, ones, unknowns):
self.ones = ones & MASK
self.unknowns = unknowns & MASK
def __add__(self, other):
x = self.ones + other.ones
u = self.unknowns | other.unknowns | (x ^ (x + self.unknowns + other.unknowns))
return Ternary(x & ~u, u)
def __or__(self, other):
o = self.ones | other.ones
return Ternary(o, (self.unknowns | other.unknowns) & ~o)
def __lshift__(self, count):
return Ternary(self.ones << count, self.unknowns << count)
def __mul__(self, other):
result = Ternary(0, 0)
for i in range(N_BITS):
if self.ones & 1 << i:
result += other << i
elif self.unknowns & 1 << i:
u = other << i
result += Ternary(0, u.ones | u.unknowns)
return result
def __repr__(self):
return ''.join('U' if self.unknowns & 1 << i else str(self.ones >> i & 1)
for i in reversed(range(N_BITS)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment