Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. import math
  2.  
  3. def get_parity_groups(code):
  4. parity_bits_am = len(code).bit_length()
  5.  
  6. groups = {}
  7.  
  8. for group in range(parity_bits_am):
  9. bit = 2 ** group
  10. for pos in range(len(code)):
  11. if (pos + 1) & bit:
  12. if len(groups) >= group + 1:
  13. groups[bit].append(pos)
  14. else:
  15. groups[bit] = [pos]
  16.  
  17. return groups
  18.  
  19. def get_parity(to_encode, group):
  20. gr_str = ""
  21. for el in group:
  22. gr_str += to_encode[el]
  23. return str(str.count(gr_str, "1") % 2)
  24.  
  25. def hammington_encode(to_encode):
  26. def get_code(to_encode, groups):
  27. parity_bits_am = len(to_encode).bit_length()
  28.  
  29. code = []
  30. for i in range(len(to_encode) + parity_bits_am):
  31. code.append("0")
  32.  
  33. for parity_bit in range(parity_bits_am):
  34. parity_val = 2 ** parity_bit
  35.  
  36. group = groups[parity_val]
  37.  
  38. code[parity_val - 1] = get_parity(to_encode, group)
  39.  
  40.  
  41.  
  42. to_fill_with = list(to_encode)
  43. i = 1
  44. while(len(to_fill_with) > 0):
  45. i += 1
  46. if math.log2(i).is_integer():
  47. continue
  48. el = to_fill_with.pop()
  49. code[i - 1] = el
  50.  
  51. return "".join(code)
  52.  
  53.  
  54. groups = get_parity_groups(to_encode)
  55. code = get_code(to_encode, groups)
  56. return code
  57.  
  58. def hammington_decode(to_decode):
  59. def get_stripped(to_decode):
  60. stripped = ""
  61. parity_bits_am = len(to_decode).bit_length()
  62.  
  63. for i in range(len(to_decode)):
  64. if math.log2(i + 1).is_integer():
  65. continue
  66. stripped += to_decode[i]
  67. return stripped
  68.  
  69. def code_check(to_decode, stripped, groups):
  70. wrong_bit = 0
  71.  
  72. parity_bits_am = len(to_decode).bit_length()
  73. for parity_bit in range(parity_bits_am):
  74. parity_val = 2 ** parity_bit
  75.  
  76. group = groups[parity_val]
  77.  
  78. check_val = to_decode[parity_val - 1]
  79. true_val = get_parity(stripped, group)
  80.  
  81. if check_val != true_val:
  82. wrong_bit |= parity_val
  83. return wrong_bit
  84.  
  85. stripped = get_stripped(to_decode)
  86. groups = get_parity_groups(stripped)
  87. wrong_bit = code_check(to_decode, stripped, groups)
  88. if wrong_bit != 0:
  89. new_code = list(to_decode)
  90. print("Wrong bit was", wrong_bit, "inversing it.")
  91. if new_code[wrong_bit - 1] == "1":
  92. new_code[wrong_bit - 1] = "0"
  93. else:
  94. new_code[wrong_bit - 1] = "1"
  95. to_decode = "".join(new_code)
  96. return get_stripped(to_decode)
  97.  
  98. c = hammington_encode("1001")
  99. print(c)
  100. print(hammington_decode(c))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement