Java Simple Encoding

The following is a method to encode a String in Java.

public String encode(String str)
{
        StringBuffer buf = new StringBuffer(str);
        int lo[] = new int[] { 48, 65, 97 };
        int hi[] = new int[] { 57, 90, 122 };
        for (int i = 0; buf != null && i < buf.length(); i++)
        {
                char ch = buf.charAt(i);
                for (int j = 0; j < lo.length; j++)
                {
                        if (ch >= lo[j] && ch <= hi[j])
                        {
                                buf.setCharAt(i, (char) (hi[j] - ch + lo[j]));
                                break;
                        }
                }
        }
        return buf.reverse().toString();
}

The encoding technique is as follows.

Store the upper and lower limit of ASCII values for characters and numbers in an array.

Retrieve a character from the given String, check whether it falls in the range between the ASCII values(a-z,A-Z,0-9).

Then find the difference between the upper limit ASCII value and the ASCII value of given character.

Now convert the resulting ASCII value to the corresponding number or character.

Repeat the same for all characters in the string and finally reverse the string.

Search