1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.