Java - Polynomial function reading hexadecimal strings as ASCII

I have a function that should read a hexadecimal number, but it does not read it correctly. A polynomial function reads a string as ASCII instead of hex.

Here is the piece of code that does 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); 
+4
source share
3 answers

String.getBytes provides default encoded characters. This is not recommended, even if you want to encode the string as bytes (assuming you provided the required encoding)

In this pase, you want to parse your hex string in bytes. An easy way to do this is to use 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)); 

prints

 [-54, -2, -70, -66] 
+3
source

Yes, String.getBytes () gets the bytes of the ascii string. Try Integer.decode (str) , assuming the line starts with "0x" or adds it yourself.

+2
source
 byte bytes[] = str.getBytes(); 

The line above uses the default platform encoding for converting characters to bytes. So, if it is ASCII and your hexadecimal string is A1 , you will get an ASCII value A followed by an ASCII value of 1.

Use a hex encoder / decoder to convert a string to bytes. I like Guava , but Apache commons-codec also has an implementation. You can also, of course, implement your own, as Peter Lowry's answer .

+1
source

All Articles