@@ -857,7 +857,7 @@ impl f32 {
857
857
let mut left = self . to_bits ( ) as i32 ;
858
858
let mut right = other. to_bits ( ) as i32 ;
859
859
860
- // In case of negatives, flip all the bits except the sign
860
+ // In case of negatives, flip all the bits expect the sign
861
861
// to achieve a similar layout as two's complement integers
862
862
//
863
863
// Why does this work? IEEE 754 floats consist of three fields:
@@ -872,13 +872,15 @@ impl f32 {
872
872
// To easily compare the floats as signed integers, we need to
873
873
// flip the exponent and mantissa bits in case of negative numbers.
874
874
// We effectively convert the numbers to "two's complement" form.
875
- if left < 0 {
876
- // i32::MAX corresponds the bit pattern of "all ones except for the sign bit"
877
- left ^= i32:: MAX
878
- } ;
879
- if right < 0 {
880
- right ^= i32:: MAX
881
- } ;
875
+ //
876
+ // To do the flipping, we construct a mask and XOR against it.
877
+ // We branchlessly calculate an "all-ones expect for the sign bit"
878
+ // mask from negative-signed values: right shifting sign-extends
879
+ // the integer, so we "fill" the mask with sign bits, and then
880
+ // convert to unsigned to push one more zero bit.
881
+ // On positive values, the mask is all zeros, so it's a no-op.
882
+ left ^= ( ( ( left >> 31 ) as u32 ) >> 1 ) as i32 ;
883
+ right ^= ( ( ( right >> 31 ) as u32 ) >> 1 ) as i32 ;
882
884
883
885
left. cmp ( & right)
884
886
}
0 commit comments