我的 Java 代码中有一个这样的字符串。
String my = "16 12 12 -119 102 105 -110 52 -89 80 -122 -68 114 20 -92 -28 -121 38 113 61"
用“”分隔的值为整数(你可以看到它)。
我可以将整数转换为 int 数组,但我需要将 int
值转换为 byte
数组。每个整数代表的值是一个字节值。
附注。
String aa[] = U.split(" ");
byte bb[] = new byte[aa.length];
for(int q=0;q<aa.length;q++){
int v = Integer.parseInt(aa[q]);
bb[q] = ???????????????????--the code I need to convert the int to a byte
}
最佳答案
你应该能够做到:
String[] parts = my.split(" ");
byte[] bytes = new byte[parts.length];
for(int i = 0; i < parts.length; i++) {
bytes[i] = Byte.parseByte(parts[i]);
}
System.out.println(Arrays.toString(bytes));
[16, 12, 12, -119, 102, 105, -110, 52, -89, 80, -122, -68, 114, 20, -92, -28, -121, 38, 113, 61]
请务必查看 Byte
类的 API,特别是 Byte.parseByte()
.
关于Java 字符串到字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25541645/