Last active
September 10, 2017 21:28
-
-
Save husobee/57bdc418d21167ab72ce989e94882b48 to your computer and use it in GitHub Desktop.
overflow-underflow-casting
This file contains hidden or 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> | |
int main() { | |
// Down Casting an unsigned long to an unsigned char | |
unsigned long a = 257; | |
printf("%lu == %d \n", a, (unsigned char)a); | |
// Output: 257 == 1 | |
// This is obviously not true, but there are not enough bits in a | |
// char (8 bits) to hold 257, so it will carry over the extra into the value | |
// Upcasting a signed negative char into an unsigned long value | |
char b = -1; | |
printf("%d == %lu \n", b, (unsigned long)b); | |
// Output: -1 == 18446744073709551615 | |
// This is obviously not true, but since computers represent signed negative | |
// numbers as ones compliment, the -1 signed char will be represented like | |
// in binary like this: 11111110 | |
// During this operation, there is an underflow. | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment