【问题标题】:Caesar Encryption and decryption C++凯撒加解密 C++
【发布时间】:2016-10-20 17:21:04
【问题描述】:

我想知道如何将加密的 ASCII 范围限制为 32 - 126。

对于我们的任务,我们应该将字符串转换为字符并加密/解密每个单独的字符。

我目前正在使用它进行加密

int value = (value-32+shift)%95+32 //value is the current ascii value of a                 
                                   //character
                                   //the first shift is given by the user with regards 
                                   //to how many shifts he wants to do to the right

这个用于解密

int value = (value-32-shift)%95+32

我的加密工作正常(当我引用解密函数时),但我的解密没有按预期工作。

额外说明:我们只需要在编码时右移,给我们整个程序加解密一个字符串(“This is C++”)

Give shift: 3
Wklv#lv#F..
DECODE 
Wklv#lv#F..  //must be 'THIS is C++'
ENCODE       //shift=15
This is C++  //must be 'cwx#/x#/R::'  
DECODE 
EYZdpZdp4{{  //must be 'THIS is C++'
ENCODE      //shift=66
cwx#/x#/R::  //must be "8LMWbMWb'mm"
DECODE 
This is C++
ENCODE       //shift=94
cwx#/x#/R::  //must be 'SGHR~hr~B**'
DECODE 
This is C++

注意:正在添加更多代码描述

【问题讨论】:

  • 我们需要minimal reproducible example。请注意那里的“最小”。我们只想看到一个固定班次,你期望的输出,和你得到的输出。

标签: c++ encryption caesar-cipher


【解决方案1】:

Modulo operator with negative values 解释了您的问题。我不确定这是完全重复的。问题是解码像“!”这样的密码字符移位不止一个(比如“3”)

int value = (value-32-shift)%95+32
          = ('!'-32-3)%95+32
          = (33-32-3)%95+32
          = (-2)%95 + 32
          = -2 + 32
          = 30

哎呀。你需要使用:

int value = (value-32+(95-shift))%95+32

【讨论】:

    【解决方案2】:

    问题是(value-32-shift) 可以变成负数。模运算不会“环绕”,而是实际上“镜像”在零附近(如果您想知道原因,请参阅this question and answer)。 为确保您的值保持正数,请在进行模运算之前添加 95:

    int value = (value-32-shift+95)%95+32
    

    【讨论】:

      猜你喜欢
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-26
      • 1970-01-01
      相关资源
      最近更新 更多