-1

Here my code in C.

unsigned int crc32b(unsigned char *message) {
   int i, j;
   unsigned int byte, crc, mask;

   i = 0;
   crc = 0xFFFFFFFF;
   while (message[i] != 0) {
      byte = message[i];            // Get next byte.
      crc = crc ^ byte;
      for (j = 7; j >= 0; j--) {    // Do eight times.
         mask = -(crc & 1);
         crc = (crc >> 1) ^ (0xEDB88320 & mask);
      }
      i = i + 1;
   }
   return ~crc;
}

But in Java, unsign int is not supported. so I try to get unsign by &0xFFFFFF

But and it wrong. How to fix it in java

Hu hu
  • 49
  • 1
  • 1
  • 5

1 Answers1

1

You can easily emulate most unsigned arithmetic with signed integers in Java (some things are more annoying, such as division, but it is not used here).

This in particular is very easy, 0xFFFFFFFF is just itself, also known as -1.

The >> should be replaced by its unsigned counterpart, >>>.

And the byte from the message has to be masked to undo the sign-extension.

In total (not tested)

int crc32b(byte[] message) {
   int i, j;
   int b, crc, mask;

   i = 0;
   crc = -1;
   while (i < message.length) {
      b = message[i] & 0xFF;        // Get next byte.
      crc = crc ^ b;
      for (j = 7; j >= 0; j--) {    // Do eight times.
         mask = -(crc & 1);
         crc = (crc >>> 1) ^ (0xEDB88320 & mask);
      }
      i = i + 1;
   }
   return ~crc;
}

That's still quite C-ish though.

harold
  • 61,398
  • 6
  • 86
  • 164