Reputation: 3115
How would I obtain a specific subset, say bits 5-10, of an int in Java?
Looking for a method where one can pass in specific bit positions. I'm not sure how I would create a mask that changes given the input, or even if that is how one should go about doing it.
I know this is how one would get the front say 10 bits of an int: (I think) int x = num >> 22;
Upvotes: 3
Views: 1468
Reputation: 15758
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:
1
bit (value: 0000000000000001
)j-i
times (value: 2^(10-5) = 2^5 = 32 = 0000000000100000
)0000000000011111
) - have you seen the lowest bits reversed?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).
Upvotes: 3
Reputation: 14883
To obtain value of bit 1 (bits are indexed from 0 to 31)
int val = bits & 0x002;
To obtain value of bit 16
int val = bits & (1<<16);
To obtain value of bit n
int val = bits & (1<<n);
Upvotes: 1