Writing a CRC function

Hi all

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?

Thanks
closed account (SECMoG1T)
You need to pad the input with n + 1 trailing zeros
you need to pad with n bits: normally your crc polynomial function will be
in the form of n+1;

example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//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  
Last edited on
Ah ok thanks. So you pretty much have to use a string?
closed account (SECMoG1T)
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.
Last edited on
Topic archived. No new replies allowed.