answersLogoWhite

0

Caeser Cipher is a substitution cipher where the character set is shifted left or right by one or more characters. That is, with a left shift of 3, the letter D in the source text becomes a letter A in the encoded text. Given the ASCII character set has 127 characters, you can left or right shift by 64 characters. For characters that result in a negative encoding, you simply add 127 to the encoding.

Example usage:

#include<iostream>

#include<exception>

#include<cassert>

char encode (int c, int shift) {

if (c<0 c>127 shift<-64 shift>64) throw std::range_error("Encoding error");

int x = c - shift;

if (x<0) x+= 127;

if (x>127) x-=127;

return (char) x;

}

char decode (int c, int shift) {

if (c<0 c>127 shift<-64 shift>64) throw std::range_error("Encoding error");

int x = c + shift;

if (x<0) x+= 127;

if (x>127) x-=127;

return (char) x;

}

int main() {

std::string source {"Hello world!"};

std::string encoded {};

std::string decoded {};

for (auto c : source) {

encoded += encode (c, 42); // shift left by 42 characters

}

assert (source != encoded);

for (auto c : encoded) {

decoded += decode (c, 42); // shift right by 42 characters

}

assert (source == decoded);

}

User Avatar

Wiki User

9y ago

What else can I help you with?