|
Re: Custom data gathering class crashes user program
We'll assume that the value you want to return is from 0-7.
This would take up three bits (unsigned) out of a byte.
bit[0] takes up the "lowest" bit, and bit[2] takes up the "highest" (going by the code you posted). If we want to arrange the bits XYZ, then bit[2] = X, bit[1] = Y, and bit[0]=Z.
The expression bit[0] evaluates to 00Z.
The expression bit[1] also evaluates to 00Y, but (bit[1]<<1) becomes 0Y0.
The expression bit[2] is 00X, but (bit[2]<<2) is X00, because it's shifted two bits to the left.
So now we have:
00Z
0Y0
X00
all as individual bits. To put those together, we just bitwise-OR them to get XYZ. The X bit is equal to 4 if it's true, the Y bit is equal to 2 if it's true, and the Z bit is 1 if it's true. An important thing to know is that (x<<n) == (x * pow(2,n)), ignoring two's complement.
__________________

GSR Dean's List Finalist 2011
|