Maxpm
Maxpm

Reputation: 25592

Comparing Bitfields of Different Sizes

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.

Upvotes: 10

Views: 11151

Answers (3)

Mark B
Mark B

Reputation: 96281

If you're actually using the values as bitfields, what's the meaning of comparing bitfields of different sizes? Would it generate a meaningful result for you?

That said, both operands will be promoted to a minimum size of int/unsigned with signedness depending on the signedness of the original operands. Then these promoted values will be compared with the bitwise operator.

This behaves as your second example: The smaller one is padded with zeroes on the MSB side (pushed to LSB side if you prefer).

If one operand is signed and negative while the other is unsigned, the negative one will be converted to the congruent unsigned number before the bit operation takes place.

If instead of integral numbers you mean std::bitset, you can't do bitwise operations on bitsets of differing sizes.

Upvotes: 2

Cristian Rodriguez
Cristian Rodriguez

Reputation: 813

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.

Upvotes: 3

Michael Burr
Michael Burr

Reputation: 340316

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.

Upvotes: 8

Related Questions