udp - C Programming - Bitwise operators and knowing when to utilize -


i have read in k&r ii c programming ansi c book ">>" , "<<" operators control bits, , of course me being noob, don't understand when use them. got interested in figuring out how build packets manually , came across 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 calculates checksum, don't understand going on here. xd

obviously out of skill range, figured can use snippet scapegoat figure out unanswered questions. when know when use bitwise operators achieve value, why not add (+) or subtract (-)? also, why there hexadecimal &0xffff there next sum, if there no operators two?

p.s. ~sum mean?

that's not a question, that's whole bunch. :)

  1. you use bitwise operators when want view number collection of bits, rather integer. it's easier "i want bit-pattern shifted 2 bits left" create mathematically equivalent operation. they're conceptually different; if think of number bits, using bit-operator makes more sense.
  2. the & 0xffff makes sure value 16 bits, masking off higher bits. assumes system's unsigned long @ least 16 bits wide, pretty safe assumption. & (bitwise and) used purpose. @ truth table logical conjunction , think "false 0, true 1" see how works.
  3. the & before hexadecimal constant c's bitwise , operator, used masking describe above. basically, single-bit variables a & b, result 1 if , if both a , b 1. operator applies logic each pair of bits in input terms.
  4. the ~ operator c's bitwise inversion, "flips" bits of argument. commonly used create masks.

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -