views:

32

answers:

2

Hi there,

I stumbled upon this piece of code while reading about DES encryption. I wonder what it does do exactly?

I see that it returns either 1 or 0 according to the result of the last if. I also understand that mask is in hexadecimal and equals 128 in decimal (why this particular value?). The for loop starts from 0 until pos%8, why? (I know that for example if pos=14 then 14%8=6).

int bit_get(const unsigned char *bits, int pos)
{
 unsigned char mask;
 int i;
 mask = 0x80;

 for (i = 0; i < (pos % 8); i++)
 mask = mask >> 1;
 return (((mask & bits[(int)(pos / 8)]) == mask) ? 1 : 0);
}

Thank you! and have a good day :)

+2  A: 
KennyTM
+1 that was my conclusion too
invariant
+1  A: 

I'm not sure why he didn't just do mask >> (pos % 8) instead of the loop.

0x80 is binary 10000000, which means you start by masking off the most significant bit, as it's the only one with a 1.

Karl Bielefeldt