开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 0

chao_qun_2020/Python

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (12)
master
cclauss-patch-1
mohammadreza490-patch-2
mohammadreza490-patch-1
codespell_--ignore-words-list
Python-3.9rc2
Delete-sleep_sort.py
pytest--durations=10
max-complexityto-15
itsvinayak-patch-1
doubly_linked_list.py-Add-doctests
Fix-ftp-to-allow-doctests
master
分支 (12)
master
cclauss-patch-1
mohammadreza490-patch-2
mohammadreza490-patch-1
codespell_--ignore-words-list
Python-3.9rc2
Delete-sleep_sort.py
pytest--durations=10
max-complexityto-15
itsvinayak-patch-1
doubly_linked_list.py-Add-doctests
Fix-ftp-to-allow-doctests
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (12)
master
cclauss-patch-1
mohammadreza490-patch-2
mohammadreza490-patch-1
codespell_--ignore-words-list
Python-3.9rc2
Delete-sleep_sort.py
pytest--durations=10
max-complexityto-15
itsvinayak-patch-1
doubly_linked_list.py-Add-doctests
Fix-ftp-to-allow-doctests
Python
/
hashes
/
hamming_code.py
Python
/
hashes
/
hamming_code.py
hamming_code.py 9.18 KB
一键复制 编辑 原始数据 按行查看 历史
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
# 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. Hamming
codes can detect up to two-bit errors or correct one-bit errors
without detection of uncorrected errors. By contrast, the simple
parity code cannot correct errors, and can detect only an odd number
of bits in error. Hamming codes are perfect codes, that is, they
achieve the highest possible rate for codes with their block length
and 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 set
as an error. This serves to check whether the code is working correctly.
Lastly, the variable of the message/word that must be desired to be
encoded (text).
* how this work:
declaration of variables (sizePari, be, text)
converts the message/word (text) to binary using the
text_to_bits function
encodes the message using the rules of hamming encoding
decodes the message using the rules of hamming encoding
print the original message, the encoded message and the
decoded message
forces an error in the coded text variable
decodes the message that was forced the error
print the original message, the encoded message, the bit changed
message and the decoded message
"""
# Imports
import 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 data
dataOrd = []
# data position template + parity
dataOutGab = []
# parity bit counter
qtdBP = 0
# counter position of data bits
contData = 0
for x in range(1, sizePar + len(data) + 1):
# Performs a template of bit positions - who should be given,
# and who should be parity
if qtdBP < sizePar:
if (np.log(x) / np.log(2)).is_integer():
dataOutGab.append("P")
qtdBP = qtdBP + 1
else:
dataOutGab.append("D")
else:
dataOutGab.append("D")
# Sorts the data to the new output size
if dataOutGab[-1] == "D":
dataOrd.append(data[contData])
contData += 1
else:
dataOrd.append(None)
# Calculates parity
qtdBP = 0 # parity bit counter
for bp in range(1, sizePar + 1):
# Bit counter one for a given parity
contBO = 0
# counter to control the loop reading
contLoop = 0
for 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 += 1
contLoop += 1
parity.append(contBO % 2)
qtdBP += 1
# Mount the message
ContBP = 0 # parity bit counter
for x in range(0, sizePar + len(data)):
if dataOrd[x] is None:
dataOut.append(str(parity[ContBP]))
ContBP += 1
else:
dataOut.append(dataOrd[x])
return dataOut
def receptorConverter(sizePar, data):
"""
>>> receptorConverter(4, "1111010010111111")
(['1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1'], True)
"""
# data position template + parity
dataOutGab = []
# Parity bit counter
qtdBP = 0
# Counter p data bit reading
contData = 0
# list of parity received
parityReceived = []
dataOutput = []
for x in range(1, len(data) + 1):
# Performs a template of bit positions - who should be given,
# and who should be parity
if qtdBP < sizePar and (np.log(x) / np.log(2)).is_integer():
dataOutGab.append("P")
qtdBP = qtdBP + 1
else:
dataOutGab.append("D")
# Sorts the data to the new output size
if dataOutGab[-1] == "D":
dataOutput.append(data[contData])
else:
parityReceived.append(data[contData])
contData += 1
# -----------calculates the parity with the data
dataOut = []
parity = []
binPos = [bin(x)[2:] for x in range(1, sizePar + len(dataOutput) + 1)]
# sorted information data for the size of the output data
dataOrd = []
# Data position feedback + parity
dataOutGab = []
# Parity bit counter
qtdBP = 0
# Counter p data bit reading
contData = 0
for x in range(1, sizePar + len(dataOutput) + 1):
# Performs a template position of bits - who should be given,
# and who should be parity
if qtdBP < sizePar and (np.log(x) / np.log(2)).is_integer():
dataOutGab.append("P")
qtdBP = qtdBP + 1
else:
dataOutGab.append("D")
# Sorts the data to the new output size
if dataOutGab[-1] == "D":
dataOrd.append(dataOutput[contData])
contData += 1
else:
dataOrd.append(None)
# Calculates parity
qtdBP = 0 # parity bit counter
for bp in range(1, sizePar + 1):
# Bit counter one for a certain parity
contBO = 0
# Counter to control loop reading
contLoop = 0
for 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 += 1
contLoop += 1
parity.append(str(contBO % 2))
qtdBP += 1
# Mount the message
ContBP = 0 # Parity bit counter
for x in range(0, sizePar + len(dataOutput)):
if dataOrd[x] is None:
dataOut.append(str(parity[ContBP]))
ContBP += 1
else:
dataOut.append(dataOrd[x])
ack = parityReceived == parity
return dataOutput, ack
# ---------------------------------------------------------------------
"""
# Example how to use
# number of parity bits
sizePari = 4
# location of the bit that will be forced an error
be = 2
# Message/word to be encoded and decoded with hamming
# text = input("Enter the word to be read: ")
text = "Message01"
# Convert the message to binary
binaryText = text_to_bits(text)
# Prints the binary of the string
print("Text input in binary is '" + binaryText + "'")
# total transmitted bits
totalBits = len(binaryText) + sizePari
print("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 error
dataOut[-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)
)
"""
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

All Algorithms implemented in Python
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/chaoqun_python/Python.git
git@gitee.com:chaoqun_python/Python.git
chaoqun_python
Python
Python
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /