原版c
/************************************************************************* Function: 16 bit CRC-CCITT calculation -------------------------------------------------------------------------- Call: calc_crc(unsigned short crc_buff, unsigned char input) -------------------------------------------------------------------------- Response: Newly calculated 16 bit CRC checksum -------------------------------------------------------------------------- Description: Calculates the checksum for 'input' in accordance with the CRC polynomial x^16 + x^12 + x^5 + 1. 'crc_buff' is the previously calculated checksum. This must be set to 0xFFFF at the beginning of a test sequence. *************************************************************************/
unsigned short calc_crc(unsigned short crc_buff, unsigned char input) {
unsigned char i;
unsigned short x16; // we’ll use this to hold the XOR mask
for (i=0; i<8; i++) { // XOR current D0 and next input bit to determine x16 value
if( (crc_buff & 0x0001) ^ (input & 0x01) )
x16 = 0x8408;
else
x16 = 0x0000;
// shift crc buffer
crc_buff = crc_buff >> 1;
// XOR in the x16 value
crc_buff ^= x16;
// shift input for next iteration
input = input >> 1;
}
return(crc_buff);
}
// ******************* MAIN ************************************
void main(void) {
// example: CRC for 8 Bytes
unsigned char values[8] = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37};
// initialise startvalue FFFFh
unsigned short crc = 0xFFFF;
// calculation
for(int n = 0; n < 8; n++)
{
crc = calc_crc(crc, values[n]);
}
// output
printf("\ndata: 30h, 31h, 32h, 33h, 34h, 35h, 36h, 37h");
printf("\nCRC: %04Xh\n", crc);
}
java 版本
public static int calc_crc(int crc_buff, char input) {
char i;
int x16;
for (i=0; i<8; i++) {
if(( (crc_buff & 0x0001) ^ (input & 0x01))>0 )
x16 = 0x8408;
else
x16 = 0x0000;
crc_buff = crc_buff >> 1;
crc_buff ^= x16;
input = (char) (input >> 1);
}
return crc_buff;
}
public static void main(String[] args) {
char values[] = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37};
int crc = 0xFFFF;
for(int n = 0; n < values.length; n++){
crc = calc_crc(crc, values[n]);
}
System.out.println(String.format("%04Xh", crc));
}
c# 版本
static void Main(string[] args)
{
byte[] values = new byte[] { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37};
int crc = 0xFFFF;
for (int n = 0; n < values.Length; n++)
{
crc = calc_crc(crc, values[n]);
}
Console.WriteLine("\ndata: 30h, 31h, 32h, 33h, 34h, 35h, 36h, 37h");
Console.WriteLine(string.Format("{0:X4}h", crc));
Console.ReadKey();
}
public static int calc_crc(int crc_buff, byte input)
{
int i;
int x16;
for (i = 0; i <8; i++)
{
if (((crc_buff & 0x0001) ^ (input & 0x01)) > 0)
x16 = 0x8408;
else
x16 = 0x0000;
crc_buff = crc_buff >> 1;
crc_buff ^= x16;
input = (byte)(input >> 1);
}
return (crc_buff);
}