0

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!

Molay
  • 1,154
  • 2
  • 19
  • 42

2 Answers2

1

Your string is a hexadecimal representation of a byte array!

With guava you can do this:

byte[] bytes = BaseEncoding.base16().decode(mystring)
Marcel Jaeschke
  • 707
  • 7
  • 24
  • it's not accepting alphanumeric ? for ex : 06038f040003800406 – Molay Mar 03 '15 at 16:35
  • 1
    If you expect lowercase letters, than you need to tell this the encoder: BaseEncoding.base16().lowerCase().decode("06038f040003800406"); http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/BaseEncoding.html – Marcel Jaeschke Mar 05 '15 at 11:54
0

I would go for:

byte[] result = myString.getBytes();

or

byte[] result = myString.getBytes(Charset.forName("UTF-8"));
Stultuske
  • 9,296
  • 1
  • 25
  • 37
  • This is not getting the actual expected result : byte[] cod = "0x0601930600058000050001".getBytes(Charset.forName("UTF-8")); for(byte b : cod){ System.out.println(b); } – Molay Mar 03 '15 at 12:10