[PATCH 07/12] Cleanup: avoid undefined shift operation

Dirk Hohndel dirk at hohndel.org
Thu Jan 4 08:50:22 PST 2018


Shifting a 32bit value by 32 is undefined.

Instead of using shifts to create the mask, explicitly create it by
subtracting 1 from the signbit value (and using bitwise NOT to fill all
the higher bits).

This commit looks confusing because Jef wanted me to not have two places
where I use the bitwise not. So instead of creating an equivalent mask
variable and not having to change the return statements we end up with a
mask that is the bitwise invert of what was there before this commit and
therefore the return statements need to change as well.

Coverity CID 207769

Suggested-by: Linus Torvalds <torvalds at linux-foundation.org>
Signed-off-by: Dirk Hohndel <dirk at hohndel.org>
---
 src/uwatec_smart_parser.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/src/uwatec_smart_parser.c b/src/uwatec_smart_parser.c
index a70acb7b91c6..bd715b03cf52 100644
--- a/src/uwatec_smart_parser.c
+++ b/src/uwatec_smart_parser.c
@@ -886,15 +886,15 @@ uwatec_smart_fixsignbit (unsigned int x, unsigned int n)
 		return 0;
 
 	unsigned int signbit = (1 << (n - 1));
-	unsigned int mask = (0xFFFFFFFF << n);
+	unsigned int mask = (signbit - 1);
 
 	// When turning a two's-complement number with a certain number
 	// of bits into one with more bits, the sign bit must be repeated
 	// in all the extra bits.
 	if ((x & signbit) == signbit)
-		return x | mask;
+		return x | ~mask;
 	else
-		return x & ~mask;
+		return x & mask;
 }
 
 
-- 
2.15.1



More information about the devel mailing list