Monday, July 28, 2008

Answer to C - Pitfalls part I

The first bug is in here:

/*get the bits which are not changed
(bit's value will be inverted when
XORed with bit 1)*/

tmp=(changedbits^(unsigned int)0x11111111);

Now, as explained in comment, the purpose is to set tmp to contain a value, where all bits which should remain same as in original value are 1, and all bits that should be changed to 0. Reason is that when we at next line use this value and AND operation with original value, we'll manage to set all bits which will be changed to 0. However the value 0x11111111 is not a value, where all bits are set to 1. A number starting with 0x is interpreted as hexadecimal value, and when we want to have a 32 bit wide value where all bits are set to 1, it is 0xFFFFFFFF.

Second bug is more of principal. The implementation shown in example will change all bits which are non zero in 'changeto' variable - regardless the changedbits variable. Correct implementation would be:

unsigned int changebytes(unsigned int const &real, unsigned int const &changedbits, unsigned int &changeto)

{
unsigned int tmp,tmp2;
/*get the bits which are not changed

(bit's value will be inverted when

XORed with bit 1)*/

tmp=(changedbits^(unsigned int)0xFFFFFFFF);
/*null the bits which will be changed.
(AND will set result to zero, if one of the bits
'anded' is zero).*/

tmp2=(real & tmp);
/*add th
e bits which should be changed from changeto in the tmp

(OR will 'sum' the bytes).*/

return (tmp2 | (changeto & changedbits));
}

No comments:

Post a Comment