简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM