Comparing Bitfields of Different Sizes

Maxpm picture Maxpm · Jun 9, 2011 · Viewed 7.4k times · Source

What happens if you use a bitwise operator (&, |, etc.) to compare two bitfields of different sizes?

For example, comparing 0 1 1 0 with 0 0 1 0 0 0 0 1:

0 1 1 0 0 0 0 0 The smaller one is extended with zeros and pushed to the
0 0 1 0 0 0 0 1 most-significant side.

Or...

0 0 0 0 0 1 1 0 The smaller one is extended with zeros and pushed to the
0 0 1 0 0 0 0 1 least-significant side.

Or...

0 1 1 0 The longer one is truncated from its least-significant side,
0 0 1 0 keeping its most significant side.

Or...

0 1 1 0 The longer one is truncated from its most-significant side,
0 0 0 1 keeping its least-significant side.

Answer

Michael Burr picture Michael Burr · Jun 9, 2011

The bitwise operators always work on promoted operands. So exactly what might happen can depend on whether one (or both) bitfields are signed (as that may result in sign extension).

So, for your example values, the bit-field with the binary value 0 1 1 0 will be promoted to the int 6, and the bit-field with the binary value 0 0 1 0 0 0 0 1 will be promoted to the int 33, and those are the operands that will be used with whatever the operation is.