Hi,
I am attempting to convert the following code written in c to
equivalent java code. This is the CRC32 algorithm used by a GPS
received I am interfacing with. Unfortunately, the CRC32 class
provided in the java API does not suit my needs because it does not
allow manipulation of the polynomial being used. Below is the original
c-code followed by my attempt to convert the code to java.
Unfortunately, my code does not produce the correct results. I assume
I am missing something in regards to the data types I am using,
specifically the change from unsigned long in c to a java int, or
something in the bit-shift operations. Any insight you can provide
would be helpful. Thanks.
c-code********************************
#define CRC32_POLYNOMIAL 0xEDB88320L
/*
--------------------------------------------------------------------------
Calculate a CRC value to be used by CRC calculation functions.
--------------------------------------------------------------------------
*/
unsigned long CRC32Value(int i)
{
int j;
unsigned long ulCRC;
ulCRC = i;
for ( j = 8 ; j > 0; j-- )
{
if ( ulCRC & 1 )
ulCRC = ( ulCRC >> 1 ) ^ CRC32_POLYNOMIAL;
else
ulCRC >>= 1;
}
return ulCRC;
}
/*
--------------------------------------------------------------------------
Calculates the CRC-32 of a block of data all at once
--------------------------------------------------------------------------
*/
unsigned long CalculateBlockCRC32(
unsigned long ulCount, /* Number of bytes in the data block */
unsigned char *ucBuffer ) /* Data block */
{
unsigned long ulTemp1;
unsigned long ulTemp2;
unsigned long ulCRC = 0;
while ( ulCount-- != 0 )
{
ulTemp1 = ( ulCRC >> 8 ) & 0x00FFFFFFL;
ulTemp2 = CRC32Value( ((int) ulCRC ^ *ucBuffer++ ) & 0xff );
ulCRC = ulTemp1 ^ ulTemp2;
}
return( ulCRC );
}
java code ************************************************
private static final int CRC32_POLYNOMIAL = 0xEDB88320;
/*
--------------------------------------------------------------------------
Calculate a CRC value to be used by CRC calculation functions.
--------------------------------------------------------------------------
*/
private static int CRC32Value(int i)
{
short j;
int ulCRC;
ulCRC = i;
for (j = 8; j > 0; j--) {
if ((ulCRC & 1) == 1)
ulCRC = (ulCRC >>> 1) ^ CRC32_POLYNOMIAL;
else
ulCRC >>>= 1;
}
return ulCRC;
}
/*
--------------------------------------------------------------------------
Calculates the CRC-32 of a block of data all at once
--------------------------------------------------------------------------
*/
public static int calculateCRC32(int length, byte[] buffer)
{
int ulTemp1;
int ulTemp2;
int ulCRC = 0;
for(int i = 0; i < length; i++) {
ulTemp1 = ( ulCRC >>> 8 ) & 0x00FFFFFF;
ulTemp2 = CRC32Value( ((int) ulCRC ^ buffer[i] ) & 0xff );
ulCRC = ulTemp1 ^ ulTemp2;
}
return ulCRC;
}