Say you have a number n
, and want bits from i
to j
(i=5, j=10).
Note, that i=0
will give you the last bit
int value = n & (((1 << (j-i)) - 1) << i );
will give you the result.
The left part is obvious: you have a value, and you will put a bitmask on it.
The value of the mask is ((1 << (j-i)) - 1) << i
. It says:
- Take a
1
bit (value: 0000000000000001
)
- Shift it left
j-i
times (value: 2^(10-5) = 2^5 = 32 = 0000000000100000
)
- Deduct 1 (value: 31 =
0000000000011111
) - have you seen the lowest bits reversed?
- Shift it left
i
times (value: 31*32=992 = 0000001111100000
)
So, you have got the bitmask for bits 5 - 10 (more precisely, from 5 to 9, since 10th is not included).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…