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"
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With