Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

269
Vistas
How to translate this working JavaScript Code to calculate CRC16 into Java

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

The expected result for the above hex String is 0000C7CF ( 51151 )

I have this working JavaScript implementation for that, which I am trying to translate to Java:

var hex = "08010000016B40D8EA30010000000000000000000000000000000105021503010101425E0F01F10000601A014E000000000000000001";

var str = '';
for (var i = 0; i < hex.length; i += 2){ 
  str += String.fromCharCode( parseInt(hex.substr(i, 2), 16) );
}

var crc = 0x0000;
var poly = 0xA001;

for (var pos = 0; pos < str.length; pos++) {
  crc ^= str.charCodeAt(pos);
  for (var i = 8; i !== 0; i--) {
    if ((crc & 0x0001) !== 0) {
      crc >>= 1;
      crc ^= poly;
    } else
      crc >>= 1;
  }
}
console.log( crc );
console.log( crc.toString(16) );

My current implementation in Java looks like this:

String hex = "08010000016B40D8EA30010000000000000000000000000000000105021503010101425E0F01F10000601A014E000000000000000001";
byte[] arr = Hex.decodeHex( hex );
long polynomial = 0xA001;
long crc = 0x0000;
for (byte b : arr) {
    crc ^= b;
    for (int i = 8; i != 0; i--) {
        if ((crc & 0x01) != 0) {
            crc >>= 1;
            crc ^= polynomial;
        } else {
            crc >>= 1;
        }
    }
}
System.out.println( crc ); // -37776

Which does not calculate the expected values. What am i doing wrong ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda