gpt4 book ai didi

Java - 将十六进制字符串读取为 ASCII 的多项式函数

转载 作者:搜寻专家 更新时间:2023-11-01 02:12:50 24 4
gpt4 key购买 nike

我有一个应该读取十六进制数的函数,但它没有正确读取它。多项式函数将字符串读取为 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);

最佳答案

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

在这一步中,您要将十六进制字符串解析为字节。一种简单的方法是使用 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]

关于Java - 将十六进制字符串读取为 ASCII 的多项式函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14092909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com