Skip to content

Instantly share code, notes, and snippets.

@stefanooldeman
Created August 27, 2018 09:58
Show Gist options
  • Save stefanooldeman/c154c6c4839ad24249cca3a98c2b88af to your computer and use it in GitHub Desktop.
Save stefanooldeman/c154c6c4839ad24249cca3a98c2b88af to your computer and use it in GitHub Desktop.
# treating each 16-bit word as an integer
# devisor = 16
# mod = (2**16-1)
words = [
int('1111111111111111', 2),
int('1111111100000000', 2),
int('1111000011110000', 2),
int('1100000011000000', 2),
]
# x = sum(b0 + b1 + b2 + ... + bL-1) modulo 2^16-1
x = sum(words) % (2**16 -1)
print("sum", x)
# the checksum is then given by bL = -x
# bL = -1 * x
bL = -1 * x
print(bL)
# 1's complement of the sum is:
checksum = bL % (2**16 -1)
print(checksum) # also called remainder?
print("generated checksum", "{0:b}".format(checksum))
## verify 0 = sum(b0 + b1 + b2 + ...+ bL-1 + bL) mod 2**16-1
verify = (x + checksum) % (2**16 -1)
print("verify", verify)
# output looks as follows run: python ip_checksum.py
# ('sum', 45234)
# -45234
# 20301
# ('generated checksum', '100111101001101')
# ('verify', 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment