简体   繁体   中英

I'm working on a cipher code using modulos and the letter “u” won't decode properly

this is the code when I run it "u" won't show if I type in "under" it will decode as "nder" I'm not sure whether it's the use of modulus or the math in my problem I've tried with many other letters and the only real issue is with "u"

#include <iostream>

std::string decode(std::string input, int shift_amount);

std::string encode(std::string input, int shift_amount);

int main(int argc, char **argv)
{
    std::string x = "{qr-or-{rny";
    std::string output;
    output = decode(x, 13);
    std::cout << output << std::endl;
}

std::string encode(std::string input, int shift_amount)
{
    for (int i = 0; i < input.length(); i++)
    {
       input[i] = (input[i] + shift_amount) % 255;
    }
    return input;
}

std::string decode(std::string input, int shift_amount)
{
    for (int i = 0; i < input.length(); i++)
    {
        input[i] = (input[i] - shift_amount) % -255;
    }
    return input;
}

Simple test:

#include <iostream>

int
main()
{
  std::cout << (- 13) % (- 255);;
  return 0;
}

The program prints -13.

The % operation is not the modulo operation , but the remainder: you will not go back to a positive number from a negative one. You have to add 255 for negative numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM