Best way to convert hex string to string in Java?

I am returning a string in the form "0x52 0x01 0x23 0x01 0x00 0x13 0xa2 0x00 0x40 0x53 0x2b 0xad 0x48 0x5f 0x30 0x30 0x31 0x33 0x41 0x32 0x30 0x30 0x34 0x30 0x35 0x33 0x32 0x42 0x41 0x41 0x41 0x41 0x41 0x41. I want to convert a hexadecimal string to a readable string - I am new to Java and did it like this:

Remove the spaces and the "x", then delete the first character, then delete every third character (which is 0).

There should be a better way to do this, but I cannot find anything worthy of Google. Help?!

+3
source share
3 answers

If you need help with the conversion you described, use the approach:

  • ( , 0x??

  • ,

  • String .

+1

( )

public class Test
{
    public static void main(String[] args)
    {
        String input = "0x52 0x01 0x23 0x01 0x00 0x13 0xa2 0x00 0x40 0x53 0x2b 0xad 0x48 0x5f 0x30 0x30 0x31 0x33 0x41 0x32 0x30 0x30 0x34 0x30 0x35 0x33 0x32 0x42 0x41 0x44";
        String[] tokens = input.split(" ");
        for(String token : tokens)
        {
            int temp = Integer.parseInt(token.substring(2, 4), 16);
            char c = (char)temp;
            System.out.print(c);
        }
    }
}

( , ). , ? (-)

+1

why not a token based 0x..
that space, zero and x it would be faster and easier, instead of deleting 2 characters in each iteration.

0
source

Source: https://habr.com/ru/post/1762558/


All Articles