python - ASCII 期望范围循环
问题描述
我在树莓派上构建了一个二维码扫描仪。我希望数据偏移量由用户设置的所需 ascii 值,以便数据有点隐藏。我希望表示的唯一 ascii 值是可打印字符 32-126。我的问题 - 例如,我希望输入偏移量为 1 的 hello。这将表示为“ifmmp”。这并不麻烦,但如果我希望表示更接近 ascii 值 126 的值,我会遇到问题,因为我得到了扩展的 ascii 字符 - 这不是我的意图。
希望你能帮忙
提前致谢
# the barcode data is a bytes object so if we want to draw it
# on our output image we need to convert it to a string first
barcodeData = barcode.data.decode("ascii")
#Change the decoded ascii string by a value of desired charcters
barcodeData = "".join(chr(ord(c) - 5) for c in barcodeData)
解决方案
您基本上试图实现的是凯撒密码的一个版本,但在整个可打印的 ASCII 范围而不是字母字符上运行。
def encode_string(s, offset):
return ''.join(chr(32+((ord(ch)-32)+offset)%95) for ch in s)
# Examples:
encode_string('~~ Hello, World! ~~', 1)
' !Ifmmp-!Xpsme"! '
encode_string(' !Ifmmp-!Xpsme"! ', -1)
'~~ Hello, World! ~~'
该%
符号称为模运算符。它计算一个数字除以另一个数字的余数。通过从初始 ASCII 值中减去 32,您会得到一个 0-94 范围内的数字。然后,您可以从中添加或减去您喜欢的任何内容,然后您可以使用此模运算符将结果限制为 0-94 范围内的另一个数字。将 32 添加到结果中,您将获得编码结果。
推荐阅读
- python-3.x - Discord.py - 传递参数角色函数
- php - LARAVEL 获取 2 个相同的列
- tensorflow-federated - 如何为单个联邦学习客户实施班级加权?
- c# - 从按钮单击方法调用私有 void 函数
- javascript - React:通过渲染道具访问组件之间传递的引用
- java - 如何在 java 中为 Amazon lex 使用 AWS lambda
- c# - 使用转换后的 appsettings 在构建管道中运行集成测试
- javascript - 如何保持两条贝塞尔曲线之间的垂直宽度相等?
- postgresql - Cloud PostgreSQL 清理大型对象vacuumlo
- c# - WPF 使用 ElementName 解决可见性问题