Tyson
Tyson

Reputation: 1238

c++: how to put relevant bits from uint32 into uint8?

I have a uint32 that I've flagged some bits on:

uint32 i = 0;
i |= (1 << 0);
i |= (1 << 5); 
i |= (1 << 13);
i |= (1 << 19);
...

I want to convert it to a uint8 (by getting the state of its first 8 bits and disregarding the rest). Obviously I could do this:

uint8 j = 0;
for (int q = 0; q < 8; q++)
{
    if (i & (1 << q))
    {
        j |= (1 << q);
    }
}

But is there a fancy bitwise operation I can use to transfer the bits over in one fell swoop, without a loop?

Upvotes: 0

Views: 2152

Answers (2)

Indranil
Indranil

Reputation: 136

You can achieve the same result by simply assigning the uint32 value to uint8.

int main()
{
  unsigned int i = 0x00000888;
  unsigned char j = i;
  cout<<hex<<i<<endl;
  cout<<hex<<+j<<endl;
  return 0;
}

output: 888 88

Upvotes: 3

Inian
Inian

Reputation: 85530

Why not just mask those last 8 bits instead of running a loop over to see if individual bits are set?

const unsigned char bitMask = 0xFF;
j = (i & bitMask);

Note that C++ 14 though allows you to define binary literals right away

const unsigned char bitMask = 0b1111'1111;

The above is all you need. Just in case, if you need to get the subsequent byte positions, use the same mask 0xFF and make sure to right shift back the result to get the desired byte value.

Upvotes: 3

Related Questions