
/*
  CLASSiC DAC, Copyright 2013 SILICON CHIP Publications
  crc.c: cyclic redundancy checks required for SD card support
  Written by Mauro Grassi and updated by Nicholas Vinen, 2009-2013
*/

typedef unsigned char BYTE;
#include "crc.h"

unsigned int CRC7(const BYTE* chr, unsigned long cnt)
{
	int i; 
	unsigned long a;
	unsigned char crc,Data; 

	crc=0; 
	for (a=0; a<cnt; a++) 
	{ 
		Data=chr[a]; 
		for (i=0;i<8;i++)
		{ 
		crc <<= 1; 
		if ((Data & 0x80)^(crc & 0x80)) 
		crc ^=0x09; 
		Data <<= 1; 
		} 
	} 
	crc=(crc<<1)|1; 
	return((unsigned int)crc); 
}

unsigned int CRC16(const BYTE* chr, unsigned long cnt)
{	
	/*
	 Compute the CRC16 of bytes at chr and cnt bytes in total
	 This routine does not use hardware CRC
	*/

	unsigned int i;
	unsigned long a;
	unsigned int crc;
	unsigned int tmp;
	
	crc=0;
	for (a=0; a<(cnt+2); a+=2) 
	{ 
		if(a==cnt)tmp=0; else tmp=((*chr)<<8)+(*(chr+1));
		chr+=2; 
		for(i=0;i<16;i++)
		{ 	
			if(crc & 0x8000)
			{
				crc<<=1;
				if(tmp & 0x8000)
				crc^=0x1020;
				else
				crc^=0x1021;
			} else
			{
				crc<<=1;
				if(tmp & 0x8000)crc|=1;
			}
			tmp<<= 1; 
		} 
	}
	return crc;
}
