Last active
April 26, 2019 08:37
-
-
Save raymondpittman/9e6daacebd3cbfd75d96a35e8020afdb to your computer and use it in GitHub Desktop.
C++ Caeser Cipher - CSC 101 - University of Southern Mississippi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Author: Raymond Pittman | |
* University of Southern Mississippi | |
* | |
* Caeser Cipher | |
* | |
* | |
*/ | |
#include <algorithm> | |
#include <cctype> | |
#include <iostream> | |
#include <string> | |
std::string | |
encrypt(std::string& s) | |
{ | |
std::transform(s.begin(), s.end(), s.begin(), | |
[](unsigned char c) -> unsigned char { | |
return int(std::toupper(c)+3-65)%26+65; | |
}); | |
return s; | |
} | |
std::string | |
decrypt(std::string& s) | |
{ | |
std::transform(s.begin(), s.end(), s.begin(), | |
[](unsigned char c) -> unsigned char { | |
return int(std::toupper(c)-3-65)%26+65; | |
}); | |
return std::string(s); | |
} | |
int | |
main() | |
{ | |
std::string A = "ABC"; // Before | |
std::cout << "Before -> " << A << std::endl; | |
encrypt(A); // Encrypted | |
std::cout << "Encrypted -> " << A << std::endl; | |
decrypt(A); // Decrypted | |
std::cout << "Decrypted -> " << A << std::endl; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Go Version | |
package main | |
func cipher(text string, direction int) string { | |
shift, offset := rune(3), rune(26) | |
runes := []rune(text) | |
for index, char := range runes { | |
switch direction { | |
case -1: // Encode | |
if char >= 'a'+shift && char <= 'z' || | |
char >= 'A'+shift && char <= 'Z' { | |
char = char - shift | |
} else if char >= 'a' && char < 'a'+shift || | |
char >= 'A' && char < 'A'+shift { | |
char = char - shift + offset | |
} | |
case +1: // Decode | |
if char >= 'a' && char <= 'z'-shift || | |
char >= 'A' && char <= 'Z'-shift { | |
char = char + shift | |
} else if char > 'z'-shift && char <= 'z' || | |
char > 'Z'-shift && char <= 'Z' { | |
char = char + shift - offset | |
} | |
} | |
runes[index] = char | |
} | |
return string(runes) | |
} | |
func encrypt(text string) string { return cipher(text, -1) } | |
func decrypt(text string) string { return cipher(text, +1) } | |
func main() { | |
println("Before - > ABC`") | |
encrypted := encrypt("ABC") | |
println("Encrypted -> " + encrypted) | |
decrypted := decrypt(encrypted) | |
println("Decrypted -> " + decrypted) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment