PDA

Click to See Complete Forum and Search --> : Checksum routine


billrogers
Oct 2nd, 2002, 09:04 AM
Can someone tell me if this works for a checksum routine?

Thanks


LOCAL u_short
nic_internet_checksum( /* _FUNC */
u_short *pAddr,
int len
)
{
int nLeft = len;
int sum = 0;
u_short *w = pAddr;
u_short answer;

while (nLeft > 1)
{
sum += *w++;
nLeft -= 2;
if (sum > 1073741824)
{
sum = (sum >> 16) + (sum & 0xffff);
}
}

if (nLeft == 1)
sum += 0 | ((*(u_char *) w) << 8);

sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
answer = sum;

return (~answer & 0xffff);
}

jim mcnamara
Oct 2nd, 2002, 12:25 PM
This use one of the standard polynomials for NIC cards -

/* crc-32 for files using autodin II, NIC polynomial 04/16/2002 4:33AM jmc*/

#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#define U_LONG unsigned int
#define U_CHAR unsigned char
#define CRC32_POLY 0x04c11db7 /* AUTODIN II, Ethernet, & FDDI */
static U_LONG crc32_table[256];
static struct stat a;

void init_crc32(void);
void test(FILE *);
U_LONG crc32(U_CHAR*,int);

int main(int argc,char *argv[]){
FILE *in;
char *buf;
if (stat(argv[1],&a)) {
printf("Cannot stat %s\n",argv[1]);
perror("Usage: crc32 <filename> \nError:");
exit(EXIT_FAILURE);
}
test(in=fopen(argv[1],"rb") );
buf=(char*)malloc(a.st_size);
fread(buf,1,a.st_size,in);
fclose(in);
init_crc32(); /* build table */
printf("%X\n", crc32((U_CHAR*)buf,a.st_size));
free(buf);
return 0;
}


U_LONG crc32(U_CHAR *buf, int len)
{
U_CHAR *p;
U_LONG crc;
crc = 0xffffffff; /* preload shift register, per CRC-32 spec */
for (p = buf; len > 0; ++p, --len)
crc = (crc << 8) ^ crc32_table[(crc >> 24) ^ *p];
return ~crc; /* transmit complement, per CRC-32 spec */
}

/*
* Build auxiliary table for parallel byte-at-a-time CRC-32.
*/


void init_crc32()
{
int i, j;
U_LONG c;

for (i = 0; i < 256; ++i) {
for (c = i << 24, j = 8; j > 0; --j)
c = c & 0x80000000 ? (c << 1) ^ CRC32_POLY : (c << 1);
crc32_table[i] = c;
}
}
/* validate file open, exit on bad file */
void test(FILE *tst){
if(tst==NULL) {
perror("Error opening input file:");
exit(EXIT_FAILURE);
}
}