I have read in the K&R II C Programming ANSI C book that the “>>” and “<<” operators control bits, and of course with me being a noob, I don’t understand when to use them. I got interested in figuring out how to build packets manually and I came across the following snippet:
unsigned short csum(unsigned short *buf, int nwords)
{
unsigned long sum;
for(sum=0; nwords>0; nwords--)
sum += *buf++;
sum = (sum >> 16) + (sum &0xffff);
sum += (sum >> 16);
return (unsigned short)(~sum);
}
I know that this calculates the checksum, but I don’t understand what is going on here. XD
Obviously this is out of my skill range, but I figured I can use this snippet as a scapegoat to figure out some unanswered questions. When do you know when to use the bitwise operators to achieve a certain value, why not just add (+) or subtract (-)? Also, why is there a hexadecimal &0xffff there next to sum, if there are no operators with the two?
P.S. What does ~sum mean?
That’s not a question, that’s a whole bunch. 🙂
& 0xffffmakes sure the value is 16 bits, by masking off all higher bits. This assumes the system’sunsigned longis at least 16 bits wide, which is a pretty safe assumption. The&(bitwiseAND) is often used for this purpose. Look at the truth table for logical conjunction and think “false is 0, true is 1” to see how this works.&before the hexadecimal constant is C’s bitwise AND operator, which is used to do the masking I describe above. Basically, for single-bit variablesa & b, the result is1if and only if bothaandbare 1. The operator applies this logic to each pair of bits in its input terms.~operator is C’s bitwise inversion, it “flips” the bits of its argument. It is commonly used to create masks.