Skip to content

Instantly share code, notes, and snippets.

@antirez
Last active May 31, 2016 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antirez/4cd940880cc0f3f553b9d4cb72c6f315 to your computer and use it in GitHub Desktop.
Save antirez/4cd940880cc0f3f553b9d4cb72c6f315 to your computer and use it in GitHub Desktop.
#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