S
S
SibVector2017-03-06 13:10:58
Programming
SibVector, 2017-03-06 13:10:58

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);

Then you need to extract these numbers, did I do it right?
a = (x >> 0 ) & 0xff;
b = (x >> 8) & 0x00ff;
c = (x >> 16) & 0x0000ffff;

If not, what's the right way? *facepalm*
Another question, what if some of the numbers, for example a , can take negative values?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
1
15432, 2017-03-06
@SibVector

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

R
Rsa97, 2017-03-06
@Rsa97

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 question

Ask a Question

731 491 924 answers to any question