-2

I received a string like this: "1F8B0800000000000003E3E6CFDBA5C820CBC0C09122ECA1C8C0F281CDC54B2138D2CF99C9D0C87866B788E9FC37860700B43D2BB325000000"

and now I want convert this string to a byte array: byte[] payload = new byte[] {0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE3, 0xE6, 0xCF, 0xDB, 0xA5, 0xC8, 0x20, 0xCB, 0xC0, 0xC0, 0x91, 0x22, 0xEC, 0xA1, 0xC8, 0xC0, 0xF2, 0x81, 0xCD, 0xC5,0x4B, 0x21, 0x38, 0xD2, 0xCF, 0x99, 0xC9, 0xD0, 0xC8, 0x78, 0x66, 0xB7, 0x88, 0xE9, 0xFC, 0x37, 0x86,0x07, 0x00, 0xB4, 0x3D, 0x2B, 0xB3, 0x25, 0x00, 0x00, 0x00 };

Can someone help me ?

Thanks

byte[] payload = new byte[] {0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE3, 0xE6, 0xCF, 0xDB, 0xA5, 0xC8, 0x20, 0xCB, 0xC0, 0xC0, 0x91, 0x22, 0xEC, 0xA1, 0xC8, 0xC0, 0xF2, 0x81, 0xCD, 0xC5,0x4B, 0x21, 0x38, 0xD2, 0xCF, 0x99, 0xC9, 0xD0, 0xC8, 0x78, 0x66, 0xB7, 0x88, 0xE9, 0xFC, 0x37, 0x86,0x07, 0x00, 0xB4, 0x3D, 0x2B, 0xB3, 0x25, 0x00, 0x00, 0x00 };

  • Maybe you can use `new BigInteger(payloadString, 16).toByteArray();`. – gthanop Mar 16 '23 at 19:06
  • 1
    but take care if the first byte is *negative*, that is, `> 0x7F` when using previous solution (could be a problem - byte `0x00` added in front to get a positive number) – user16320675 Mar 16 '23 at 19:07
  • 1
    `byte[] a = HexFormat.of().parseHex(s);`( >= Java 17) – g00se Mar 16 '23 at 21:15
  • 2
    See [Convert a string representation of a hex dump to a byte array using Java? - Stack Overflow](https://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java). – モキャデ Mar 16 '23 at 21:21

1 Answers1

0

You can do it as follows.

String hexString = "1F8B0800000000000003E3E6CFDBA5C820CBC0C09122ECA1C8C0F281C"
        + "DC54B2138D2CF99C9D0C87866B788E9FC37860700B43D2BB325000000";

Without a doubt, the simplest way is to use what g00se said in the comments above.

byte[] bytes = HexFormat.of(hexString).parseHex(s);

If you are running releases java 8 thru Java 16 the following will work.

  • match two characters at a time and stream the results.
  • convert the hex string in the capture group to a decimal byte
  • then collect in an Byte array.
Byte[] bytes = Pattern.compile("(..)").matcher(hexString).results()
        .map(mr -> (byte)Integer.parseInt(mr.group(), 16))
        .toArray(Byte[]::new);


WJS
  • 36,363
  • 4
  • 24
  • 39