Tyairah Tyairah - 2 months ago 7
Java Question

How do I get the value of an ASCII code in Java?

I am trying to return an array of values from a string of values. However, my code returns the ASCII code values of the string that has been inputted. Here is my code, a test case, and what it currently returns.

public static int[] stringToBigInt(String s) {
int []A = new int [SIZE];

int j = s.length() - 1;
for (int i = A.length - 1; j >= 0 && i >= 0; --i){
A[i] = s.charAt(j);
--j;
}

return A;
}

System.out.println("Test 8: Should be\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 4, 1, 5, 9, 2]");
System.out.println(Arrays.toString( stringToBigInt( "3141592" ) ));
System.out.println();


Run:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51, 49, 52, 49, 53, 57, 50]

Answer

Here's another way:

Just subtract the char with the '0' char.

public static int[] stringToBigInt(String s) {
        int []A = new int [SIZE];

        int j = s.length() - 1;
        for (int i = A.length - 1; j >= 0 && i >= 0; --i){
            A[i] = s.charAt(j) - '0';
            --j;
        }

        return A;   
    }

Output is:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 4, 1, 5, 9, 2]