views:

70

answers:

3

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?!

+1  A: 

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.

Amir Afghani
+1  A: 

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)

Catchwa
I agreed with this solution up to char c = (char)temp. user375566 should plug in a conversion from an int into a readable string (whatever that means) there. One possibility would be System.out.print(" " + temp ).
emory
@emroy - casting the int into a char is the most conventional conversion from an int ASCII value into a readable String. I think the problem is either the input hex values or the ambiguity in the question itself.
Catchwa
A: 

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.

p01ntbl4nk
any comments from others?
Louis Rhys
for the input "0x20 0x30 0x40" tokening based on " 0x" as suggested would deliver tokens of ["0x20", "30", "40"]
Catchwa