如何将“0xCA”字符串转换为字节?

How to convert "0xCA" String to byte?

我有一个超过 100000 字节的大文件,看起来像这样 "0xCA,0xFE,0xBA,0xBE,0x0,0x0,0x0,0x34,0x0,0xBB,0x1,0x0,0x35,0x6D,0x65, 0x2F, 0x6D" 我想检索文件的内容并将每个字节作为字节存储在字节数组中,我的 jar 将它们检索为字符串但无法将它们转换为功能字节我该怎么做?

    public static byte[] genClasses() throws IOException {
    InputStream stream = LonelyMod.class.getResourceAsStream("/o.txt");
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    ArrayList<Byte> bytes = new ArrayList<>();
    String line;
    while((line = reader.readLine()) != null) {
        ArrayList<Byte> tempBytes = new ArrayList<>();
        for(String s : line.split(",")) {
            tempBytes.add(/* here im supposed to add the s String as a byte*/);
        }
        bytes.addAll(tempBytes);
    }
    byte[] bytes1 = new byte[bytes.size()];
    int i = 0;
    for(byte b : bytes) {
        bytes1[i] = b;
        i++;
    }
    return bytes1;
}

感谢您的帮助

给定以下字符串。

String s ="0xCA,0xFE,0xBA,0xBE,0x0,0x0,0x0,0x34,0x0,0xBB,0x1,0x0,0x35,0x6D,0x65,0x2F,0x6D";

您可以按照以下方式进行:

// remove the hex prefix and split on ','
String[] tokens = s.replace("0x","").split(",");

// allocate a byte array to hold the results
byte[] bytes = new byte[tokens.length];

//now parse to an int and assign to a byte.  Only the low order
// 8 bits will be assigned.
int i = 0;
for (String str : tokens) {
    bytes[i++] = (byte) Integer.parseInt(str,16);
}

for (byte b : bytes)
    System.out.print(b + " ");
}

版画

-54 -2 -70 -66 0 0 0 52 0 -69 1 0 53 109 101 47 109 

由于有些大于 127,因此它们将作为有符号值打印。

我马上就发现了一个问题。 0xCA > byte.MAX_VALUE,因此给它一个 -54 的值而不是 202 的 int 值。如果这是你想要的,那么这里是它的代码。如果不是,则只需删除字节转换并将 x 设置为 int 即可。

    byte x = (byte)0;
    if(myByte.length() == "0xCA".length())
    x = (byte)((myByte.substring(0, 1).equals("0") ? 1 : -1) * (myByteVal(myByte.substring(2,3)) * 16 + myByteVal(myByte.substring(3,4))));
    else if(myByte.length() == "0x0".length())
    x = (byte)((myByte.substring(0, 1).equals("0") ? 1 : -1) * (myByteVal(myByte.substring(2,3))));

我创建的获取值的方法在这里:

public static int myByteVal(String x) {
        x = x.toLowerCase();
        return x.equals("0") ? 0 : x.equals("1") ? 1 : x.equals("2") ? 2 : x.equals("3") ? 3 : x.equals("4") ? 4 : x.equals("5") ? 5 : x.equals("6") ? 6 : x.equals("7") ? 7 : x.equals("8") ? 8 : x.equals("9") ? 9 : x.equals("a") ? 10 : x.equals("b") ? 11 : x.equals("c") ? 12 : x.equals("d") ? 13 : x.equals("e") ? 14 : 15;
    }

从@WJS 的回答中获得灵感,这是另一种方法,在这种情况下使用 Integer.decode 可以接受您已经拥有的 0x 格式的整数:

String s ="0xCA,0xFE,0xBA,0xBE,0x0,0x0,0x0,0x34,0x0,0xBB,0x1,0x0,0x35,0x6D,0x65,0x2F,0x6D";

Arrays.stream(s.split(","))
        .map(Integer::decode)
        .map(Integer::byteValue)
        .forEach(b -> System.out.printf(" %d", b));