javahex

Java String, single char to hex bytes


I want to convert a string by single char to 5 hex bytes and a byte represent a hex number:

like

String s = "ABOL1";

to

byte[] bytes = {41, 42, 4F, 4C, 01}

I tried following code , but Byte.decode got error when string is too large, like "4F" or "4C". Is there another way to convert it?

String s = "ABOL1";
char[] array = s.toCharArray();
for (int i = 0; i < array.length; i++) {
  String hex = String.format("%02X", (int) array[i]);
  bytes[i] = Byte.decode(hex);
}                

Solution

  • Use String hex = String.format("0x%02X", (int) array[i]); to specify HexDigits with 0x before the string.

    A better solution is convert char into byte directly:

    bytes[i] = (byte)array[i];
    

    a char is an integral type in Java