javaarrayshexbytenumber-systems

Converting String to byte array for hex values


I am using a Android Phone to communicate with a BLE device.

The method to send data for the library needs byte[], sharing one of the static example snippet:

 public static final byte dataRequest[] = { 0x23,  0x57,  0x09,  0x03, (byte) 0xD4};
 sendDataToDevice(dataRequest);

The data i am receiving from the user is in String, for example

String str1 = "D4";

now my question is , how to convert this String value (which is actually a hex value in String datatype) to byte, so that i can store these dynamic String values and convert and then insert it into byte[] like ,

byte[0] = convertToByte(str1);

where byte[0] must store value as 0xD9 or like the format given in static example.


Solution

  • You should just be able to use Integer#parseInt with a radix of 16 (hexadecimal) to convert a String to an int (which you can then cast to a byte and store in your array):

    String str1 = "D4";
    byte b = (byte) Integer.parseInt(str1, 16);
    System.out.println(b);
    

    Output:

    -44
    

    Note: Byte#parseByte can't be used in your example, as Byte#parseByte uses Integer#parseInt internally and parses D4 as 212, which is not a valid value for a signed byte.