首页 > 解决方案 > 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)

标签: pythonraspberry-piasciioffset

解决方案


您基本上试图实现的是凯撒密码的一个版本,但在整个可打印的 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 添加到结果中,您将获得编码结果。


推荐阅读