From ca79610cfbf6675c744a6d37d186d713dd70843c Mon Sep 17 00:00:00 2001 From: datalore Date: Fri, 27 Oct 2023 16:43:19 +0200 Subject: [PATCH] Fixed integer overflow issue in shifting --- brute.cc | 5 +++-- shift.cc | 5 +++-- vigenere.cc | 5 +++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/brute.cc b/brute.cc index f663e2a..7d99c10 100644 --- a/brute.cc +++ b/brute.cc @@ -10,10 +10,11 @@ void shift(char* text, int key) std::cout << ' '; continue; } - char c = std::tolower(text[i])-key; + // has to be int, because the result can sometimes be > 127 + int c = std::tolower(text[i])-key; if(c < 'a') c+=26; if(c > 'z') c-=26; - std::cout << c; + std::cout << (char)c; } std::cout << std::endl; } diff --git a/shift.cc b/shift.cc index c4694c8..f8cdd9a 100644 --- a/shift.cc +++ b/shift.cc @@ -20,10 +20,11 @@ int main(int argc, char** argv) std::cout << ' '; continue; } - char c = std::tolower(text[i])+key; + // has to be int, because the result can sometimes be > 127 + int c = std::tolower(text[i])+key; if(c < 'a') c+=26; if(c > 'z') c-=26; - std::cout << c; + std::cout << (char)c; } std::cout << std::endl; return 0; diff --git a/vigenere.cc b/vigenere.cc index 6880a8d..29b2dc0 100644 --- a/vigenere.cc +++ b/vigenere.cc @@ -25,10 +25,11 @@ int main(int argc, char** argv) std::cout << ' '; continue; } - char c = std::tolower(text[pi]) + keyvalue(key[ki]); + // has to be int, because the result can sometimes be > 127 + int c = std::tolower(text[pi]) + keyvalue(key[ki]); if(c < 'a') c+=26; if(c > 'z') c-=26; - std::cout << c; + std::cout << (char)c; if(key[++ki] == 0) ki = 0; } std::cout << std::endl;