I'd like to write a CRC function (for fun obviously!). I've read on wikipedia about how the algorithm works but I'm a little unsure how to implement it.
1. You need to pad the input with n + 1 trailing zeros (where n is the bitlength of the CRC result). How do you do this padding in practice?
2. If your input consists of multiple characters (bytes), how do you 'join' these together to form your input?
//let's say
std::string crc_poly = "110101"///6 bits = n+1 bits polynomial
std::string pad(crc_poly.size()-1,'0'); ///"00000"
///If your input consists of multiple characters (bytes), how do you 'join' these together
//if your input say is:
std::string data_chunk("hello there");///convert to bin
std::string str_to_bin(const std::string& data)
{
std::string result{};
for(auto ch : data)///each character is 1 byte
{
std::bitset<8> bits(ch);
result += bits.to_string();
}
return result;
}
auto chunk_bin = str_to_bin(data_chunk);//our chunk is in binary form
///lets pad it with the n zeros
chunk_bin += pad;///mission complete, chunk_bin is now your input
///now you can go ahead XOR'ing chunk_bin with your polynomial
So you pretty much have to use a string?
it basically depends with how much you are reading or writing, you can write
in sequences of single bytes(1 char),8 bytes(8 chars) or n bytes(n chars),
depends on what you want or your limitations, for example in networking there is a max number of chars you can receive/send at once.
for the crc code size you generate, it simply depends with you input polynomial code : e.g a 6 bits polynomial of (n+1) form will generate a 5 bits(n) crc code.