Friday 10 February 2023

Integer shift gotcha

 Left shifting values seems simple, but the following code contains a bug:

 
The literal value 1 is actually a signed int, so the promotion to a uint64_t type will sign extend the value before assigning to x, causing x to be 0xffffffff80000000.
 
The fix is simple, just make the literal value 1 an unsigned int using 1U instead of 1.
 
 
 

No comments:

Post a Comment