Question

I am encoding a string using the following method

public String encrypt(String data)
{             
        encoded = data.getBytes();
        String str_encoded = java.util.Arrays.toString(encoded);

        System.out.println("encoded:" + java.util.Arrays.toString(encoded));

        return str_encoded;
}

How do i decode the encoded string to get back my original string .

For example : "abc123" when encoded will be [97, 98, 99, 49, 50, 51]

How do i decode [97, 98, 99, 49, 50, 51] back into "abc123"

i am sure its quite simple , but i cant figure it out

Was it helpful?

Solution

Simply use below code. Create an byte[] and form the String.

String decoded = new String(new byte[]{97, 98, 99, 49, 50, 51});

Complete code:

String[] bytes = str_encoded.substring(1, str_encoded.length() - 1).split(", ");

byte[] bytesArray = new byte[bytes.length];
for (int i = 0; i < bytesArray.length; i++) {
    bytesArray[i] = Integer.valueOf(bytes[i]).byteValue();
}

String str_decoded = new String(bytesArray);
System.out.println(str_decoded);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top