确实使用
Byte.parseByte(String)
这样做:
public static byte[] toByteArray(String[] arr) {
byte[] res = new byte[arr.length];
for (int i = 0; i < arr.length; i++)
res[i] = Byte.parseByte(arr[i]);
return res;
}
附笔。
在
Java
字节值是
〔128;128〕
. 因此
"128"
将投掷
java.lang.NumberFormatException: Value out of range. Value:"128" Radix:10
. 必须决定要对这些值执行什么操作:抛出异常,因为使用数据无效;或者将其转换为最接近的字节值,如
"128" -> 127
;甚至忽略这些价值观。这段代码可能是这样的:
public static byte[] toByteArray(String[] arr) {
byte[] res = new byte[arr.length];
for (int i = 0; i < arr.length; i++) {
try {
res[i] = Byte.parseByte(arr[i]);
} catch(Exception e) {
res[i] = // TODO action for incorrect value
}
}
return res;
}