开发者

Comparing Bitfields of Different Sizes

开发者 https://www.devze.com 2023-03-12 06:43 出处:网络
What happens if you use a bitwise operator (&, |, etc.) to compare two 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 on开发者_JAVA技巧e is truncated from its most-significant side,
0 0 0 1 keeping its least-significant side.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号