I need to get 4 ints from a integer with the following format
int1 14 bits
int2 14 bits
int3 3 bits
int4 1 bit
I've found a lot of articles for reading individual bits from an int but I can't find anything on reading multiple values from a single integer so and help would be appreciated!
Asuming it is from left to right
int int1 = x >> 18;
int int2 = (x >> 4) & 0x3fff;
int int3 = (x >> 1) & 7;
int int4 = x & 1;
You can use bitwise and to get this:
int source = somevalue;
int int1 = 16383&somevalue;
int int2 = 268419072&somevalue;
int int3 = 1879048192&somevalue;
So let's assume your 32-bit int is arranged bit-wise as follows, and your target variables are X, Y, Z and W.
31 0 # bit index
XXXXXXXXXXXXXX YYYYYYYYYYYYYY ZZZ W # arrangement
......14...... ......14...... .3. 1 # bits per variable
............18 .............4 ..1 0 # required right-shift
To get at X
, you would shift your integer right by 18 bits, then mask it by ((1<<14)-1)
(that is 0x3FFF), etc.:
x = (i >> 18) & 0x3FFF
y = (i >> 4) & 0x3FFF
z = (i >> 1) & 7 # ((1<<3)-1) = 7
w = i & 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.