# Author: João Gustavo A. Amorim & Gabriel Kunz# Author email: joaogustavoamorim@gmail.com and gabriel-kunz@uergs.edu.br# Coding date: apr 2019# Black: True"""* This code implement the Hamming code:https://en.wikipedia.org/wiki/Hamming_code - In telecommunication,Hamming codes are a family of linear error-correcting codes. Hammingcodes can detect up to two-bit errors or correct one-bit errorswithout detection of uncorrected errors. By contrast, the simpleparity code cannot correct errors, and can detect only an odd numberof bits in error. Hamming codes are perfect codes, that is, theyachieve the highest possible rate for codes with their block lengthand minimum distance of three.* the implemented code consists of:* a function responsible for encoding the message (emitterConverter)* return the encoded message* a function responsible for decoding the message (receptorConverter)* return the decoded message and a ack of data integrity* how to use:to be used you must declare how many parity bits (sizePari)you want to include in the message.it is desired (for test purposes) to select a bit to be setas an error. This serves to check whether the code is working correctly.Lastly, the variable of the message/word that must be desired to beencoded (text).* how this work:declaration of variables (sizePari, be, text)converts the message/word (text) to binary using thetext_to_bits functionencodes the message using the rules of hamming encodingdecodes the message using the rules of hamming encodingprint the original message, the encoded message and thedecoded messageforces an error in the coded text variabledecodes the message that was forced the errorprint the original message, the encoded message, the bit changedmessage and the decoded message"""# Importsimport numpy as np# Functions of binary conversion--------------------------------------def text_to_bits(text, encoding="utf-8", errors="surrogatepass"):""">>> text_to_bits("msg")'011011010111001101100111'"""bits = bin(int.from_bytes(text.encode(encoding, errors), "big"))[2:]return bits.zfill(8 * ((len(bits) + 7) // 8))def text_from_bits(bits, encoding="utf-8", errors="surrogatepass"):""">>> text_from_bits('011011010111001101100111')'msg'"""n = int(bits, 2)return n.to_bytes((n.bit_length() + 7) // 8, "big").decode(encoding, errors) or "0円"# Functions of hamming code-------------------------------------------def emitterConverter(sizePar, data):""":param sizePar: how many parity bits the message must have:param data: information bits:return: message to be transmitted by unreliable medium- bits of information merged with parity bits>>> emitterConverter(4, "101010111111")['1', '1', '1', '1', '0', '1', '0', '0', '1', '0', '1', '1', '1', '1', '1', '1']"""if sizePar + len(data) <= 2 ** sizePar - (len(data) - 1):print("ERROR - size of parity don't match with size of data")exit(0)dataOut = []parity = []binPos = [bin(x)[2:] for x in range(1, sizePar + len(data) + 1)]# sorted information data for the size of the output datadataOrd = []# data position template + paritydataOutGab = []# parity bit counterqtdBP = 0# counter position of data bitscontData = 0for x in range(1, sizePar + len(data) + 1):# Performs a template of bit positions - who should be given,# and who should be parityif qtdBP < sizePar:if (np.log(x) / np.log(2)).is_integer():dataOutGab.append("P")qtdBP = qtdBP + 1else:dataOutGab.append("D")else:dataOutGab.append("D")# Sorts the data to the new output sizeif dataOutGab[-1] == "D":dataOrd.append(data[contData])contData += 1else:dataOrd.append(None)# Calculates parityqtdBP = 0 # parity bit counterfor bp in range(1, sizePar + 1):# Bit counter one for a given paritycontBO = 0# counter to control the loop readingcontLoop = 0for x in dataOrd:if x is not None:try:aux = (binPos[contLoop])[-1 * (bp)]except IndexError:aux = "0"if aux == "1":if x == "1":contBO += 1contLoop += 1parity.append(contBO % 2)qtdBP += 1# Mount the messageContBP = 0 # parity bit counterfor x in range(0, sizePar + len(data)):if dataOrd[x] is None:dataOut.append(str(parity[ContBP]))ContBP += 1else:dataOut.append(dataOrd[x])return dataOutdef receptorConverter(sizePar, data):""">>> receptorConverter(4, "1111010010111111")(['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True)"""# data position template + paritydataOutGab = []# Parity bit counterqtdBP = 0# Counter p data bit readingcontData = 0# list of parity receivedparityReceived = []dataOutput = []for x in range(1, len(data) + 1):# Performs a template of bit positions - who should be given,# and who should be parityif qtdBP < sizePar and (np.log(x) / np.log(2)).is_integer():dataOutGab.append("P")qtdBP = qtdBP + 1else:dataOutGab.append("D")# Sorts the data to the new output sizeif dataOutGab[-1] == "D":dataOutput.append(data[contData])else:parityReceived.append(data[contData])contData += 1# -----------calculates the parity with the datadataOut = []parity = []binPos = [bin(x)[2:] for x in range(1, sizePar + len(dataOutput) + 1)]# sorted information data for the size of the output datadataOrd = []# Data position feedback + paritydataOutGab = []# Parity bit counterqtdBP = 0# Counter p data bit readingcontData = 0for x in range(1, sizePar + len(dataOutput) + 1):# Performs a template position of bits - who should be given,# and who should be parityif qtdBP < sizePar and (np.log(x) / np.log(2)).is_integer():dataOutGab.append("P")qtdBP = qtdBP + 1else:dataOutGab.append("D")# Sorts the data to the new output sizeif dataOutGab[-1] == "D":dataOrd.append(dataOutput[contData])contData += 1else:dataOrd.append(None)# Calculates parityqtdBP = 0 # parity bit counterfor bp in range(1, sizePar + 1):# Bit counter one for a certain paritycontBO = 0# Counter to control loop readingcontLoop = 0for x in dataOrd:if x is not None:try:aux = (binPos[contLoop])[-1 * (bp)]except IndexError:aux = "0"if aux == "1" and x == "1":contBO += 1contLoop += 1parity.append(str(contBO % 2))qtdBP += 1# Mount the messageContBP = 0 # Parity bit counterfor x in range(0, sizePar + len(dataOutput)):if dataOrd[x] is None:dataOut.append(str(parity[ContBP]))ContBP += 1else:dataOut.append(dataOrd[x])ack = parityReceived == parityreturn dataOutput, ack# ---------------------------------------------------------------------"""# Example how to use# number of parity bitssizePari = 4# location of the bit that will be forced an errorbe = 2# Message/word to be encoded and decoded with hamming# text = input("Enter the word to be read: ")text = "Message01"# Convert the message to binarybinaryText = text_to_bits(text)# Prints the binary of the stringprint("Text input in binary is '" + binaryText + "'")# total transmitted bitstotalBits = len(binaryText) + sizePariprint("Size of data is " + str(totalBits))print("\n --Message exchange--")print("Data to send ------------> " + binaryText)dataOut = emitterConverter(sizePari, binaryText)print("Data converted ----------> " + "".join(dataOut))dataReceiv, ack = receptorConverter(sizePari, dataOut)print("Data receive ------------> "+ "".join(dataReceiv)+ "\t\t -- Data integrity: "+ str(ack))print("\n --Force error--")print("Data to send ------------> " + binaryText)dataOut = emitterConverter(sizePari, binaryText)print("Data converted ----------> " + "".join(dataOut))# forces errordataOut[-be] = "1" * (dataOut[-be] == "0") + "0" * (dataOut[-be] == "1")print("Data after transmission -> " + "".join(dataOut))dataReceiv, ack = receptorConverter(sizePari, dataOut)print("Data receive ------------> "+ "".join(dataReceiv)+ "\t\t -- Data integrity: "+ str(ack))"""
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。