Reputation: 189
I am a java programmer and trying to learn c++ . i have a working CRC32 function but it takes chars from an array and calculate its CRC32.
i want to read a file and calculate file's CRC32.
Should i read the file, split it and put all the data to array or is there any easy ways?
unsigned int crc32(unsigned char *message) {
int i, j;
unsigned int byte, crc;
i = 0;
crc = 0xFFFFFFFF;
while (message[i] != 0) {
byte = message[i]; // Get next byte.
crc = crc ^ byte;
for(j = 7; j>=0; j--){
crc = (crc >> 1) ^ (crc & 1 ? 0xEDB88320 : 0);
}
i = i + 1;
}
return ~crc;
}
int main()
{
unsigned char a[] = {'e',0};
cout << std::hex <<"0x" << crc32(a);
return 0;
}
Upvotes: 1
Views: 1559
Reputation: 8781
You can load the file in one chunk with the fread or stream APIs and apply your crc32 function on that. Or you can load it in pieces and apply the function that way. For files above a certain size, that's the best way to go around, although you can get to pretty big sizes indeed without requiring any chuncking (thanks to x64 large address spaces, virtual memory handled by the OS, memory mapping etc).
In general, regardless of programming languages, the same principles for designing programs apply, more or less - what you get by switching languages are different APIs, different abstractions (though more and more languages seem to be converging on the same set of class based object orientation, lambdas, async/await etc). The same advice would be valid for Python, Java, C++, Ruby etc
Upvotes: 1