1

I'm reading (binary) data from file and generating the CRC16 checksum. The next step is to write this checksum at the end of this file (as last 2 bytes) and then calculate CRC16 again which should be 0. The problem is the CRC which i wrote to the file is different. For example i use write(reinterpret_cast<const char *>(&crc), 2) to writeshort int crc = 0xba10 at the end, but in fact im writing ş which is 00010000 11000101 10011111 not 10111010 00010000.Is there any way to write it properly at the end of file?

Here is my crc calculating code:

int crc16(char* data_p, int length){
unsigned char x;
unsigned short crc = 0x1D0F; 

while (length--){
    x = crc >> 8 ^ *data_p++;
    x ^= x >> 4; // x = x ^ (x >> 4)
    crc = (crc << 8) ^ ((unsigned short)(x << 12)) ^ ((unsigned short)(x <<5)) ^ ((unsigned short)x);
}
return crc;
}
KaDw
  • 78
  • 1
  • 7
  • 2
    a) You have a little-endian machine, that's why 0x10 byte (the low-order byte) comes first. That's entirely expected and unsurprising. b) It seems that, somehow, your file is being written as text file with UTF-8 encoding - that's how 0xBA byte gets encoded as two bytes. – Igor Tandetnik Jan 11 '15 at 16:42
  • [`std::ofstream::write()`](http://en.cppreference.com/w/cpp/io/basic_ostream/write) perhaps, and using a `uint16_t` as return type and to hold the checksum. – πάντα ῥεῖ Jan 11 '15 at 16:43
  • `data_p` should be `unsigned char *`, and the algorithm doesn't look correct. – user207421 Jan 11 '15 at 16:44
  • @Igor a) same problem, I was trying it before b) yes i think sth is wrong with encoding – KaDw Jan 11 '15 at 16:54
  • @EJP what is wrong with it? – KaDw Jan 11 '15 at 16:56
  • `same problem, I was trying it before` What problem? What were you trying before? – Igor Tandetnik Jan 11 '15 at 16:58
  • I mean my machine is not little-endian. – KaDw Jan 11 '15 at 17:01
  • It doesn't look like a CRC-16 checksum algorithm, that's what's wrong with it. Are you sure it's correct? I would have expected to see XOR with a constant, and not see the >> 4 line. There's a table-driven version which is eight times as fast. – user207421 Jan 11 '15 at 17:21
  • @EJP I was searching for simple algorithm. If u have any better algorithm post it here. – KaDw Jan 11 '15 at 17:32
  • Where did you get this one? Try Wikipedia. – user207421 Jan 11 '15 at 17:40
  • post by Antonio Pires: http://stackoverflow.com/questions/10564491/function-to-calculate-a-crc16-checksum – KaDw Jan 11 '15 at 17:46
  • 1
    You should be looking at the accepted answer there, by @MichaelBurr. – user207421 Jan 11 '15 at 22:22

0 Answers0