unsigned n = 8;
unsigned low8bits = n & 0xFF;
Note a few things:
- For bitwise operations, always use the
unsigned
types
- Bits can be extracted from numbers using binary masking with the
&
operator
- To access the low 8 bits the mask is
0xFF
because in binary it has its low 8 bits turned on and the rest 0
- The low 8 bits of the number 8 are... 8 (think about it for a moment)
To access a certain bit of a number, say the k
th bit:
unsigned n = ...;
unsigned kthbit = (1 << k) & n;
Now, kthbit
will be 0 if the k
th bit of n
is 0, and some positive number (2**k
) if the k
th bit of n
is 1.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…