凯撒加密和解密c++

Caesar Encryption and decryption C++

本文关键字:c++ 解密 加密 凯撒      更新时间:2023-10-16

我想知道如何限制ASCII加密范围从32到126。

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

我现在使用这个来加密

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

我的加密工作完美(当我引用解密函数时),但我的解密工作不像它应该的那样。

额外注意:我们只需要在编码时做一个右移,为整个程序提供一个字符串来加密和解密("这是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++

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

您的问题在具有负值的模算子中解释。我不确定这是不是一模一样的复制品。问题是,解码像'!

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

问题是(value-32-shift)可以变为负值。模运算并不是"绕着",而是实际上"绕着"零(如果你想知道为什么,请参阅这个问题并回答)。要确保您的值为正,请在进行模运算之前加上95:

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