Answer the question
In order to leave comments, you need to log in
How to correctly extract numbers from a bit field?
You need to store three numbers in an int field:
int a = 4, b = 7, c = 5;
int x = (c << 16) | (b << 8) | a);
a = (x >> 0 ) & 0xff;
b = (x >> 8) & 0x00ff;
c = (x >> 16) & 0x0000ffff;
Answer the question
In order to leave comments, you need to log in
Correctly. Leading zeros are not needed, just 0xFF or 0xFFFF. But it can be easier:
struct BitField{
union{
int value;
struct{
int a:8;
int b:8;
int c:16;
};
};
};
BitField MyBits;
MyBits.a = 4; //fill the internal bit structure
MyBits.b = 7;
MyBits.c = 5;
cout << MyBits.value; //print the full int representation
The question of "correctness" is primarily about the range of values that a , b , and c can take .
Your notation will work for a and b from 0 to 255 and c from 0 to 32767.
In principle, you can work with negative values, but you need to complete the sign when converting back, like this ( a from -128 to 127)
a = x & 0xFF;
if (a & 0x80)
a &= -1;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question