Skip to content

Instantly share code, notes, and snippets.

@grocid
Last active October 28, 2019 23:19
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 grocid/739e38a5f5ee452698b556ecc6df03e6 to your computer and use it in GitHub Desktop.
Save grocid/739e38a5f5ee452698b556ecc6df03e6 to your computer and use it in GitHub Desktop.
Exponentiation in GF2[x]/P(x)
import math
poly = 0xa195150d15*2+1
degree = int(math.log(poly)/math.log(2))
f = (1 << degree)
def multiply(a, b, poly):
r = 0
for i in range(64):
if ((a & (1 << i)) != 0):
r ^= b
b = (b << 1)
if (b & f):
b ^= poly
return r
def exp(x, n, poly):
if n == 0:
return 1
y = 1
while n > 1:
if n % 2 == 0:
x = multiply(x, x, poly)
n = n / 2
else:
y = multiply(x, y, poly)
x = multiply(x, x, poly)
n = (n - 1) / 2
return multiply(x, y, poly)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment