[英]Converting String to byte array for hex values
I am using a Android Phone to communicate with a BLE device.我正在使用 Android 手机与 BLE 设备进行通信。
The method to send data for the library needs byte[], sharing one of the static example snippet:为库发送数据的方法需要byte[],共享静态示例片段之一:
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.其中 byte[0] 必须将值存储为 0xD9 或类似于静态示例中给出的格式。
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):您应该能够使用radix
为16
(十六进制)的Integer#parseInt
将String
转换为int
(然后您可以将其转换为一个byte
并存储在您的数组中):
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
.注意: Byte#parseByte
不能在您的示例中使用,因为Byte#parseByte
Integer#parseInt
内部使用Integer#parseInt
并将D4
解析为212
,这不是有符号byte
的有效值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.