Last active
May 31, 2016 08:57
-
-
Save antirez/4cd940880cc0f3f553b9d4cb72c6f315 to your computer and use it in GitHub Desktop.
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
#include <stdio.h> | |
#include <limits.h> | |
int main(void) { | |
int a; | |
unsigned int b; | |
a = -10; | |
printf("Before: %d\n", a); | |
b = a; /* If a is negative, b will be converted adding UINT_MAX + 1. */ | |
if (b > INT_MAX) { | |
/* b > INT_MAX only if the above conversion happened. We need to | |
* subtract UNIT_MAX + 1. | |
* | |
* UINT_MAX + 1 = (INT_MAX+1)*2 so we need to subtract | |
* INT_MAX + 1 two times. | |
* | |
* First: subtract INT_MAX+1 from the unsigned integer. */ | |
b = b - INT_MAX - 1; | |
/* Convert to signed, we should now always be within range. */ | |
a = b; | |
/* Finally subtract it again to reconstruct the original value. */ | |
a = a - INT_MAX - 1; | |
} else { | |
a = b; | |
} | |
printf("After: %d\n", a); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment