I have a function that is supposed to read a hex number, but it is not reading it correctly. The polynomial function is reading the string as ASCII instead of hex.
Here is the portion of code that is doing the work:
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 gives you the characters with the default character encoding. It is not recomended evenm if you want to encode a String as bytes (it is suggest you provide the encoding you want)
In this pase you want to parse your hexidecimal string into bytes. A simple way to do this is to use BigInteger.
prints