Created
March 14, 2017 21:16
-
-
Save musteresel/87d877d83cb2afb92eb8721a9d29adc7 to your computer and use it in GitHub Desktop.
Promote some value to an unsigned integer type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
uint32_t a = (...); | |
uint32_t b = a << 31; | |
When uint32_t is defined as a short type, then both operands of the | |
shift will get promoted to int. Thus above code is then equivalent to: | |
unsigned short a = (...); | |
unsigned short b = (unsigned short)((int)a << 31); | |
THIS IS UNDEFINED BEHAVIOUR, though. (Shifting a negative value) | |
Solution: Promote to an unsigned type before shifting: | |
uint32_t b = PROMOTE_AT_LEAST_UNSIGNED(a) << 31; | |
Source: http://stackoverflow.com/q/39964651/1116364 | |
*/ | |
#define PROMOTE_AT_LEAST_UNSIGNED(x) ((x) + 0u) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment