repl.it
@simontiger/

Parity & Checksum

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def parity(message, debug=False):
  bytes = [ord(i) for i in message]

  parity = False
  debug_out = ""

  for byte in bytes:
    for i in range(8):
      if byte & (0x80 >> i):
        parity = not parity
        debug_out += "1"
      else:
        debug_out += "0"
    debug_out += " "
  
  debug_out += "1" if parity else "0"

  if debug: print(debug_out)
  return parity

def checksum(message, debug=False):
  bytes = [ord(i) for i in message]

  checksum = 0
  debug_out = ""

  for byte in bytes:
    checksum += byte
    debug_out += "\n  "
    for i in range(8):
      debug_out += "1" if byte & (0x80 >> i) else "0"
  
  debug_out += "\n----------"
  debug_out += "\n" + bin(checksum)[2:]

  if debug: print(debug_out)
  return parity

checksum("Hello, world!", True)