十六进制到字节[]的Java字符串

问题描述 投票:-4回答:3

它需要转换字符串,如:

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;

任何人都可以帮忙吗?谢谢!

java byte
3个回答
3
投票
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不能使用。


1
投票
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);

我添加了一些关于此代码如何工作的评论。

我使用整数而不是字节的原因是给定字符串中有一些溢出字节的十六进制值。


0
投票

如果您100%确定每个数字都以0x开头,那么您可以将其子串,然后使用Integer.parseInt(substringed, 16)解析它。

© www.soinside.com 2019 - 2024. All rights reserved.