4

我有一个应该读取十六进制数字的函数,但它没有正确读取它。多项式函数将字符串读取为 ASCII 而不是十六进制。

这是正在执行工作的代码部分:

JButton button = new JButton("Calculate");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String str = textArea.getText();

                      int crc = 0xFFFF;        
                     int polynomial = 0x1021;  

                        byte bytes[] = str.getBytes();
                     for (byte b : bytes) {
                         for (int i = 0; i < 8; i++) {
                             boolean bit = ((b   >> (7-i) & 1) == 1);
                             boolean c15 = ((crc >> 15    & 1) == 1);
                             crc <<= 1;
                             if (c15 ^ bit) crc ^= polynomial;
                          }
                     }
                     crc &= 0xFFFF;
                textField.setText(""+Integer.toHexString(crc));
            }
        });
        button.setBounds(10, 245, 90, 25);
        panel.add(button);
4

3 回答 3

3

String.getBytes 为您提供具有默认字符编码的字符。如果要将字符串编码为字节,则不建议使用(建议您提供所需的编码)

在这种情况下,您想将十六进制字符串解析为字节。一个简单的方法是使用 BigInteger。

String hex = "CAFEBABE";
byte[] bytes = new BigInteger(hex, 16).toByteArray();
if (bytes.length > 0 && bytes[0] == 0)
    bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
System.out.println(Arrays.toString(bytes));

印刷

[-54, -2, -70, -66]
于 2012-12-30T17:45:07.737 回答
2

是的, String.getBytes() 为您获取 ascii 字符串的字节。尝试Integer.decode(str),假设字符串以“0x”开头,或者自己添加。

于 2012-12-30T17:39:51.890 回答
1
byte bytes[] = str.getBytes();

上面的行使用您平台的默认编码将字符转换为字节。因此,如果它是 ASCII 并且您的十六进制字符串是A1,您将获得 A 的 ASCII 值,然后是 1 的 ASCII 值。

使用十六进制编码器/解码器将字符串转换为字节。我喜欢Guava,但 Apache commons-codec也有一个实现。您当然也可以按照Peter Lawrey 的回答显示自己的实现。

于 2012-12-30T17:41:50.357 回答