bitwise operators - calculate parity bit from string in c -


i trying calculate parity bit in string using following code, first calculate paritybyte string , calculate paritybit byte, have gathered these functions should trick right i'm not sure, program in use them fails, , if it's because of these or if should other place.

char calculateparity(char *payload, int size){     char r = 0;     int i;     for(i = 0; < size; i++){         r ^= payload[i];     }     return calcparitybit(r); }  char calcparitybit(char x){     x ^= x >> 8;     x ^= x >> 4;     x ^= x >> 2;     x ^= x >> 1;     return x & 1; } 

as @squeamish ossifrage comments: use unsigned char calculation. char may signed, right shifting may replicate sign bit.

further, code typically runs best return value of int versus char. recommend using return value of int or bool.

// find parity (of width width of unsigned) int calcevenparitybit(unsigned par, unsigned width) {   while (width > 1) {     par ^= par >> (width/2);       width -= width/2;   }    // return least significant bit   return par % 2; }  int calculateevenparity(char *payload, int size) {   unsigned char r = 0;   int i;   for(i = 0; < size; i++) {     r ^= payload[i];   }   return calcevenparitybit(r, char_bit); } 

invert result odd parity.


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -