Question

I'm trying to convert a small string of hexadecimal numbers into a array of integers, not very successfully until now. I have tried to find such problems on multiple websites, but most came up with the hexadecimal number simply being to large, which is not the case here. Current code:

static String decode(String message) {
        int indexC = 0;
        int asciiCode = 0;
        String [] codeArray = message.split(" ");
        int [] asciiArray = new int[4];

        while (indexC < codeArray.length){
            asciiCode = Integer.parseInt(codeArray[indexC]);
            asciiArray[indexC] = asciiCode;
        }
            for (int i = 0; i < asciiArray.length; i++){
        System.out.println(asciiArray[i]);  
            }
    }

I do get a result for the system.out.println but instead of 4 numbers i'd expect, it prints the same (hex) numbers that i started with (in this case: 44 74 71 20)

I am not allowed to include extra libraries or packages, i can only work with codes and classes i create myself. The point of my code is to get the decimal values. the println is only to check what i got (but if somebody know how to print that line correctly, please respond as well ;) ).

(little more background info: i'm building a simple encryptor for text, i'm working on the decoder now, and i need the ascii values connected to the hexadecimal numbers)

Was it helpful?

Solution 2

You need to provide the conversion method Integer.parseInt(String s, int radix) with a radix, (which is 16 for Hex), so you need to change this line

asciiCode = Integer.parseInt(codeArray[indexC]);

to

asciiCode = Integer.parseInt(codeArray[indexC], 16);

The reason why you get the same numbers out is because if you don't provide the radix then it defaults to 10.

OTHER TIPS

[I@221a5d08 is is the string representation of the array object itself not the content of the array.

If you want to print its content, use Arrays.toString(int [] a):

System.out.println(Arrays.toString(asciiArray));

If you're not allowed to use this method you can implement a simple for loop:

for(int i = 0; i < asciiArray.length; i++)
    System.out.print(asciiArry[i]);

You're printing the address of the array, a common mistake. Use System.out.println(Arrays.toString(asciiArray)) instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top