0

I have the two inverse inverse functions:

public static BigInteger stringToBig(String message) {      
    StringBuilder sb = new StringBuilder();
    for (char c : message.toCharArray()) {
        sb.append((int)c);
    }

    return new BigInteger(sb.toString());
}

public static String bigStringToString(String string) {
    StringBuilder result = new StringBuilder();
    for (int x = (string.length() % 3 - 3) % 3; x < string.length(); x += 3) {
        int chr = Integer.parseInt(string.substring(Math.max(x, 0), x + 3));
        result.append(Character.toString((char) (chr)));
    }
    return result.toString();
}

My goal is to take the string from

"This is my message"

Convert it to "8410410511532105115321091213210910111511597103101"

and then convert it back to "This is my message"

I've tried the following but get "????is?[ÕÒ?o??ge" back as an output from bigStringToString

String text = String.valueOf(stringToBig("This is my message"));
System.out.println(text);
System.out.println(bigStringToString(text));

What's wrong with my conversion back?

4
  • 4
    Your transform isn't reversible. The digits 123 could be 1 then 2 then 3, or it could be 12 and 3, or 1 and 23, or literally 123. Commented May 23, 2018 at 20:44
  • 3
    What makes you think char is ASCII? It's actually UTF-16. Commented May 23, 2018 at 20:45
  • @ElliottFrisch Ah, yup Commented May 23, 2018 at 20:47
  • … and the decimal digits that Character.MAX_VALUE requires could be … or 65535. Try "🚲" for the message. Commented May 23, 2018 at 23:05

2 Answers 2

2

Your current transform isn't reversible, instead you can use the byte[] from String.getBytes() directly. And don't forget to specify an encoding. Something like,

String s = "This is my message";
try {
    byte[] enc = s.getBytes("UTF-8");
    BigInteger val = new BigInteger(enc);
    System.out.println(val);
    System.out.println(new String(val.toByteArray(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

Outputs

7352961551138726160548009928799764296591205
This is my message
Sign up to request clarification or add additional context in comments.

Comments

2

As indicated by others, you are not accounting for the different lengths of integers. Since you assume all characters are ascii and have length 3, you can use this when constructing the string for the BigInteger:

 sb.append(String.format("%03d", (int) c));

Comments

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.