#include #include typedef unsigned char byte; void show_bytes(void * start, size_t len){ printf("\t%lu bytes from %p:", len, start); int i; for(i = 0; i < len; i++){ printf(" %.2x", ((byte *) start)[i]); } printf("\n"); } void casting_demo_shorter(){ printf("\nCasting from longer to shorter:\n"); int x1 = -5; int x2 = 5; int x3 = 24967291; short y1 = (short) x1; short y2 = (short) x2; short y3 = (short) x3; printf("\t(short) -5 = %d\n",y1); show_bytes(&x1,4); show_bytes(&y1,2); printf("\n\t(short) 5 = %d\n",y2); show_bytes(&x2,4); show_bytes(&y2,2); printf("\n\t(short) 2294967291 = %d\n",y3); show_bytes(&x3,4); show_bytes(&y3,2); } void casting_demo_longer(){ printf("\nCasting from shorter to longer:\n"); short x1 = -5; short x2 = 5; int y1 = (int) x1; int y2 = (int) x2; printf("\t(int) -5 = %d\n",y1); show_bytes(&x1,2); show_bytes(&y1,4); printf("\n\t(int) 5 = %d\n",y2); show_bytes(&x2,2); show_bytes(&y2,4); } void casting_demo_signed_unsigned(){ printf("Casting from signed to unsigned:\n"); int x1 = -5; int x2 = 5; unsigned int y1 = (unsigned int) x1; unsigned int y2 = (unsigned int) x2; printf("\t(unsigned int) -5 = %u\n",y1); show_bytes(&x1,4); show_bytes(&y1,4); printf("\n\t(unsigned int) 5 = %u\n",y2); show_bytes(&x2,4); show_bytes(&y2,4); } void casting_demo_unsigned_signed(){ printf("\nCasting from unsigned to signed:\n"); unsigned int x1 = 5; unsigned int x2 = 4294967291; int y1 = (int) x1; int y2 = (int) x2; printf("\t(int) 5 = %d\n",y1); show_bytes(&x1,4); show_bytes(&y1,4); printf("\n\t(int) 4294967291 = %d\n",y2); show_bytes(&x2,4); show_bytes(&y2,4); } void why_unsigned_is_dangerous(){ int cnt = 8; int a[cnt]; for(int x = 0; x < cnt; x++){ a[x] = x; } unsigned int i; for(i = cnt-2; i >= 0; i--){ a[i] += a[i+1]; printf("i = %u, a[%u] = %d\n",i,i,a[i]); } } void exercise3(){ char a = -30; char b = 21; char x; x = ~a; printf("~(-30) = %d\n",x); x = !a; printf("!(-30) = %d\n",x); x = a & b; printf("-30 & 21 = %d\n",x); x = a && b; printf("-30 && 21 = %d\n",x); x = a << 2; printf("-30 << 2 = %d\n",x); x = a >> 2; printf("-30 >> 2 = %d\n",x); x = b >> 2; printf("21 >> 2 = %d\n",x); } int main(int argc, char ** argv){ casting_demo_shorter(); casting_demo_longer(); casting_demo_signed_unsigned(); casting_demo_unsigned_signed(); //why_unsigned_is_dangerous(); //exercise3(); return 0; }