ASCII期望范围循环

问题描述 投票:0回答:1

我已经在树莓派上构建了QR码扫描仪。我希望将数据偏移用户设置的所需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)
python raspberry-pi ascii offset
1个回答
0
投票

您基本上想要实现的是Caesar密码的一个版本,但是在整个可打印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,就可以返回编码结果。

© www.soinside.com 2019 - 2024. All rights reserved.