Comparison of bitfields of different sizes

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

For example, a comparison of 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. 
+6
source share
3 answers

Bitwise operators always work on advanced operands. So exactly what can happen may depend on whether one (or both) bit fields are signed (since this can lead to an extension of the character).

So, for your example values, a bit field with a binary value of 0 1 1 0 will advance to int 6 , and a bit field with a binary value of 0 0 1 0 0 0 0 1 will advance to int 33 , and these are the operands that will be be used with any operation.

+7
source

0 0 0 0 0 1 1 0 The smallest is expanded by zeros and pushed to 0 0 1 0 0 0 0 1 the least significant side.

+1
source

If you use values ​​as bit fields, then what's the point of comparing bit fields of different sizes? Will it bring you meaningful results?

Nevertheless, both operands will be increased to a minimum size of int / unsigned with signature depending on the signature of the source operands. Then these advanced values ​​will be compared with the bitwise operator.

This behaves like your second example: the smaller one is padded with zeros on the MSB side (if you prefer it on the LSB side).

If one operand is signed and negative and the other unsigned, the negative will be converted to a congruent unsigned number before the bit occurs.

If instead of integers you mean std::bitset , you cannot perform bitwise operations on bits of different sizes.

+1
source

Source: https://habr.com/ru/post/890168/


All Articles