Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert set of ascii characters back to string

I currently have a situation where I am converting string to ascii characters:

        String str = "are";  // or anything else

        StringBuilder sb = new StringBuilder();
        for (char c : str.toCharArray())
            sb.append((int)c);

        BigInteger mInt = new BigInteger(sb.toString());
        System.out.println(mInt);

where output (in this case) is 97114101 I am struggling to find a way how to reverse this, convert string of ascii characters back to a string e.g. "are"

like image 998
Ilja Avatar asked Dec 14 '13 11:12

Ilja


3 Answers

You cannot do it with decimal numbers, because the number of digits in their representation changes. Because of this, you wouldn't be able to distinguish sequences 112 5 from 11 25 and 1 125.

You could force each character to occupy exactly three digits, however. In this case, you would be able to restore the number back by repeatedly dividing by 1000, and taking the remainder:

for (char c : str.toCharArray()) {
    String numStr = String.valueOf((int)c);
    while (numStr.length() != 3) numStr = "0"+numStr;
    sb.append(numStr);
}

If you use only the ASCII section of the UNICODE code points, this is somewhat wasteful, because the values that you need are for the most part two-digit. If you switch to hex, all ASCII code points would fit in two digits:

for (char c : str.toCharArray()) {
    String numStr = Integer.toString(c, 16);
    if (numStr.length() == 1) numStr = "0"+numStr;
    sb.append(numStr);
}
BigInteger mInt = new BigInteger(sb.toString(), 16);

Now you can use division by 256 instead of 1000.

like image 186
Sergey Kalinichenko Avatar answered Sep 18 '22 07:09

Sergey Kalinichenko


The simple answer is that you cant as you have lost data. You have no way of knowing how many digits each character had.

You need some sort of separator between the numbers.

like image 22
Tim B Avatar answered Sep 19 '22 07:09

Tim B


The answer is a big No, You cannot get it back with your existing approach.

Instead you can have an integer array (if possible). You may get best solution if you explain why you are actually doing this.

like image 41
Suresh Atta Avatar answered Sep 22 '22 07:09

Suresh Atta