1

I am trying to decode the string encoded by the function below. I tried to reverse the encryption by doing c -= c-i, but it doesn't seem to work. Can anyone please explain how does this work?

public static String encode(String message){
        StringBuilder b = new StringBuilder();
        for(int i = 0;i<message.length();i++){
            char c = message.charAt(i);
            b.append(c +=  c+i);
        }
        return b.reverse().toString();
    }
2
  • I don't understand the reason for downvote? Commented Apr 26, 2018 at 2:43
  • Arithmetic on character codes is a bit sketchy (@Elliot alludes to unstated conditions for this algorithm). That's why encryption libraries take in bytes and put out bytes. If you want to convert text to bytes, you'd apply a character encoding (such as UTF-8), and visa versa. If you want to handle encryped bytes (or any non-text bytes) as text, you'd use Base64 or similar. Commented Apr 27, 2018 at 23:26

1 Answer 1

5

Your encoding is reversible (for small messages and some set of the charset), but your formula is incorrect. First, reverse the message (to decode). Then iterate the characters. Subtract i from the current value, and then divide by 2. Like,

public static String decode(String message) {
    StringBuilder b = new StringBuilder(message).reverse();
    StringBuilder o = new StringBuilder();
    for (int i = 0; i < b.length(); i++) {
        char c = b.charAt(i);
        c -= i;
        c /= 2;
        o.append(c);
    }
    return o.toString();
}

Math: c += c + i; is equivalent to c = (2 * c) + i

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation. Now i understand the math behind it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.