Java String, single char to hex bytes

15,660

Solution 1

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

A better solution is convert int into byte directly:

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

Solution 2

Is there any reason you are trying to go through string? Because you could just do this:

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

Or even replace all this code with:

byte[] bytes = s.getBytes(StandardCharsets.US_ASCII);

Solution 3

You can convert from char to hex String with String.format():

String hex = String.format("%04x", (int) array[i]);

Or threat the char as an int and use:

String hex = Integer.toHexString((int) array[i]);
Share:
15,660

Related videos on Youtube

Sarah0050
Author by

Sarah0050

Updated on September 15, 2022

Comments

  • Sarah0050
    Sarah0050 over 1 year

    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);
    }                
    
    • fge
      fge about 9 years
      A char is not a byte!
    • user207421
      user207421 about 9 years
      There is no such thing as a 'hex byte'. The data is already in the format you require. Just copy the bytes.