Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 796
Maxpm Avatar asked Jun 09 '11 16:06

Maxpm


3 Answers

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.

like image 136
Michael Burr Avatar answered Nov 05 '22 17:11

Michael Burr


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.

like image 20
crodriguezo Avatar answered Nov 05 '22 19:11

crodriguezo


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.

like image 45
Mark B Avatar answered Nov 05 '22 18:11

Mark B