Skip to content

Commit 6c16c23

Browse files
rtang09pre-commit-ci[bot]cclauss
authored andcommitted
Fletcher 16 (TheAlgorithms#9775)
* Add files via upload * Update fletcher16.py * Update fletcher16.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update fletcher16.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update fletcher16.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Update fletcher16.py --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 197a17d commit 6c16c23

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

hashes/fletcher16.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
The Fletcher checksum is an algorithm for computing a position-dependent
3+
checksum devised by John G. Fletcher (1934–2012) at Lawrence Livermore Labs
4+
in the late 1970s.[1] The objective of the Fletcher checksum was to
5+
provide error-detection properties approaching those of a cyclic
6+
redundancy check but with the lower computational effort associated
7+
with summation techniques.
8+
9+
Source: https://en.wikipedia.org/wiki/Fletcher%27s_checksum
10+
"""
11+
12+
13+
def fletcher16(text: str) -> int:
14+
"""
15+
Loop through every character in the data and add to two sums.
16+
17+
>>> fletcher16('hello world')
18+
6752
19+
>>> fletcher16('onethousandfourhundredthirtyfour')
20+
28347
21+
>>> fletcher16('The quick brown fox jumps over the lazy dog.')
22+
5655
23+
"""
24+
data = bytes(text, "ascii")
25+
sum1 = 0
26+
sum2 = 0
27+
for character in data:
28+
sum1 = (sum1 + character) % 255
29+
sum2 = (sum1 + sum2) % 255
30+
return (sum2 << 8) | sum1
31+
32+
33+
if __name__ == "__main__":
34+
import doctest
35+
36+
doctest.testmod()

0 commit comments

Comments
 (0)