Category Archives: apache-commons-codec

Convert String to byte array (0x) – Java

I have a String value as "0x0601930600058000050001", need to convert to byte array

byte[] codes1 = new byte[]{(byte)0x06,(byte)0x01,(byte)0x93,(byte)0x06,(byte)0x00,(byte)0x05,(byte)0x80,(byte)0x00,(byte)0x05,(byte)0x00,(byte)0x01};

    for(byte b : codes1){
        System.out.println(b);
    }
System.out.println("======================");

byte[] cod = "0x0601930600058000050001".getBytes();
for(byte b : cod){
        System.out.println(b);
    }

Both the results are different, how to make them same. 1st loop output is the actual one what i am expecting, 2nd loop is wrong output.

If you see, i am splitting each 2 bytes and type casting and using 0x to get the actual value.

Question : Is there any predefined method (Apache commons codec) which can help me to do the same task as 1st loop ? I get that String value dynamically at run time.

Please suggest.

Thanks!