Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fletcher 16 #9775

Merged
merged 9 commits into from
Oct 5, 2023
Merged
36 changes: 36 additions & 0 deletions hashes/fletcher16.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""
The Fletcher checksum is an algorithm for computing a position-dependent
checksum devised by John G. Fletcher (1934–2012) at Lawrence Livermore Labs
in the late 1970s.[1] The objective of the Fletcher checksum was to
provide error-detection properties approaching those of a cyclic
redundancy check but with the lower computational effort associated
with summation techniques.

Source: https://en.wikipedia.org/wiki/Fletcher%27s_checksum
"""


def fletcher16(text: str) -> int:
"""
Loop through every character in the data and add to two sums.

>>> fletcher16('hello world')
6752
>>> fletcher16('onethousandfourhundredthirtyfour')
28347
>>> fletcher16('The quick brown fox jumps over the lazy dog.')
5655
"""
data = bytes(text, "ascii")
sum1 = 0
sum2 = 0
for character in data:
sum1 = (sum1 + character) % 255
sum2 = (sum1 + sum2) % 255
return (sum2 << 8) | sum1


if __name__ == "__main__":
import doctest

doctest.testmod()