Hello I have the below c function which I believe to be in the correct specification for CRC-16 CCITT False:
uint16_t crc16(const char* pData, int length)
{
uint8_t i;
uint16_t wCrc = 0xffff;
while (length--) {
wCrc ^= *(unsigned char *)pData++ << 8;
for (i=0; i < 8; i++)
wCrc = wCrc & 0x8000 ? (wCrc << 1) ^ 0x1021 : wCrc << 1;
}
return wCrc & 0xffff;
}
I am using Objective C for my application and have the following:
- (IBAction)mycrc16function:(id)sender
{
NSString * stringexample = @"Example";
const char * stringAsChar = [stringexample cStringUsingEncoding:[NSString defaultCStringEncoding]]; //encode string into c string encoding
unsigned long CrcTest = crc16(stringAsChar,sizeof(stringAsChar)); // put encoded string date and size of string into the crc16 function.
NSLog(@"crctext %04lX\n",CrcTest); // print outcome to log
}
The output is always incorrect, the string I am testing with for example is giving a result of 6B20
However the result should be E272
I am using this site which I know to be correct to compare my results: http://www.sunshine2k.de/coding/javascript/crc/crc_js.html
Any idea where I am going wrong?
const char * stringAsCharused as argument for a function that expects aunsigned long. Alsosizeof(stringAsChar)is rather strange as it does not depend on the length of that string.sizeof()should be as wrong here as it is in puce C. Just usestrlen()if you have a nul terminated string. Btw. mymain()is basicallyuint16_t wCrc = crc16(argv[1], strlen(argv[1]);