I need to calculate a CRC on a block of data that matches a CRC calculation done in an 8 bit microcontroller (8051 using Keil C51 compiler).
The CRC is calculated on a block of 512 bytes according to the Get_Buf_CRC() function below:
I have created these "matching" functions in B4J:
but, should I be surprised? the results don't match...
I have been having much pain with the type conversions in Java from byte to unsigned int and such and it's probably another one of those cases...
Any help or suggestion appreciated.
Note that I am not bound to that particular implementation or even that type of CRC, it's just that the C version results in very small code space utilization and I have very little code space available, so I would like to use it.
TIA
The CRC is calculated on a block of 512 bytes according to the Get_Buf_CRC() function below:
B4X:
uint Get_Buf_CRC( uchar *ptr, uint numbytes ){
uint i, CRC;
CRC = 0x0000;
// Process each byte in the buffer into the running CRC
for( i = 0; i < numbytes; i++ ){
CRC = Update_CRC( CRC, *ptr++ );
}
return( CRC );
}
uint Update_CRC( uint crc, uchar newbyte ){
uchar i; // loop counter
#define POLY 0x8408 // CRC16-CCITT FCS (X^16+X^12+X^5+1)
crc = crc ^ newbyte;
for( i = 0; i < 8; i++ ){
if( crc & 0x01 ){
crc = crc >> 1;
crc ^= POLY;
}else{
crc = crc >> 1;
}
}
return( crc );
}
I have created these "matching" functions in B4J:
B4X:
Sub Get_Buf_CRC( buf_offset As Int, numBytes As Int) As Int ' needs unsigned int16
Dim crc As Int = 0, i As Int
For i = 0 To numBytes-1
crc = UpdateCRC( crc, mHexImage(buf_offset + i))
Next
Return crc
End Sub
Sub UpdateCRC( crc As Int, newbyte As Byte ) As Int
Dim CRCpoly As Int = 0x8408 ' CRC16-CCITT FCS (X^16+X^12+X^5+1)
Dim i As Int
crc = Bit.Xor( crc, newbyte )
For i = 0 To 7
If Bit.And( crc, 0x0001 ) = 1 Then
crc = crc/2
crc = Bit.Xor( crc, CRCpoly )
Else
crc = crc/2
End If
Next
Return crc
End Sub
but, should I be surprised? the results don't match...
I have been having much pain with the type conversions in Java from byte to unsigned int and such and it's probably another one of those cases...
Any help or suggestion appreciated.
Note that I am not bound to that particular implementation or even that type of CRC, it's just that the C version results in very small code space utilization and I have very little code space available, so I would like to use it.
TIA