它需要转换字符串,如:
String test = "0xF0 0x9F 0x87 0xB7 0xF0 0x9F 0x87 0xBA";
String [] GetByte = test.split(" ");
字节数组如:
byte [] test_arr = new byte [GetByte.length];
test [0] = (byte) 0xF0;
test [1] = (byte) 0x9F;
test [2] = (byte) 0x87;
test [3] = (byte) 0xB7;
test [4] = (byte) 0xF0;
test [5] = (byte) 0x9F;
test [6] = (byte) 0x87;
test [7] = (byte) 0xBA;
任何人都可以帮忙吗?谢谢!
String[] words = test.split(" ");
byte[] bytes = new byte[words.length];
for (int i = 0; i < words.length; ++i) {
//bytes[i] = Byte.decode(words[i]);
bytes[i] = Integer.decode(words[i]).byteValue();
}
方法decode
也将翻译其他基础。
不幸的是byte
签了,所以0xF0
溢出,Byte.decode
不能使用。
Integer[] numbers =
//splitting the string into an array and converting it to a stream
Arrays.stream(test.split(" "))
//removing '0x' from each hex string and parsing an integer value from it
.map(s -> Integer.parseInt(s.replace("0x", ""), 16))
//collecting everything to an integer array
.toArray(Integer[]::new);
我添加了一些关于此代码如何工作的评论。
我使用整数而不是字节的原因是给定字符串中有一些溢出字节的十六进制值。
如果您100%确定每个数字都以0x
开头,那么您可以将其子串,然后使用Integer.parseInt(substringed, 16)
解析它。