user375566
user375566

Reputation:

Best way to convert hex string to string in Java?

I am returned a string in the form of "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". I want to convert the hex string into a readable string - I am new to Java, and was going about it this way:

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

There has got to be a better way to do this, but I can't seem to find anything Google-worthy. Help?!

Upvotes: 3

Views: 3300

Answers (3)

p01ntbl4nk
p01ntbl4nk

Reputation: 50

why not token based on 0x..
that's a space, a zero and an x
it would be faster and easier instead of having to remove 2 chars on every iteration.

Upvotes: 0

Catchwa
Catchwa

Reputation: 5855

This should work in theory (I think)

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);
        }
    }
}

However, I'm getting strange output (run it and you'll see). Is the input string supposed to make sense? (English-wise)

Upvotes: 1

Amir Afghani
Amir Afghani

Reputation: 38531

If you'd like help accomplishing the conversion you described, here's an approach:

  • Split the String based on spaces (now you have an array of strings that look like 0x??

  • For each element in the array, remove what don't like

  • Create a String and concatenate each of the array elements into the newly created String.

Upvotes: 1

Related Questions