Skip to content

Instantly share code, notes, and snippets.

@husobee

husobee/overunder.c

Last active Sep 10, 2017
Embed
What would you like to do?
overflow-underflow-casting
#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