Skip to content
Advertisement

Why does the same bitwise calculation yield different results in Java and JavaScript?

Problem:

I need to calculate a CRC16 for hex codes like this one:

08010000016B40D8EA30010000000000000000000000000000000105021503010101425E0F01F10000601A014E000000000000000001

For this, I have a working solution in JavaScript. Due to new requirements, I have to translate this code into Java.

Expected result:

For above hex string: 0000C7CF ( 51151 ).

My approach:

I have the following, working JavaScript code, which I am trying to translate into Java:

JavaScript

My current implementation in Java looks like this:

JavaScript

As you can see, the translated Java code does not calculate the expected result.

Question:

Why does this code yield different results in Java and JavaScript?

Advertisement

Answer

Change the following line from

crc ^= b

to

crc ^= (b & 0xff)

In java, byte ranges from -128 to 127, so you have to make it unsigned.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement