#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 exercise1(){ char x1 = 47; char x2 = -47; char x3 = 0x86; char x4 = 0x25; printf("x1 = %d (0x%hhx)\n", x1, x1); printf("x2 = %d (0x%hhx)\n", x2, x2); printf("x3 = %d (0x%hhx)\n", x3, x3); printf("x4 = %d (0x%hhx)\n", x4, x4); } 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) %d = %d\n", x1, y1); show_bytes(&x1,4); show_bytes(&y1,2); printf("\n\t(short) %d = %d\n", x2, y2); show_bytes(&x2,4); show_bytes(&y2,2); printf("\n\t(short) %d = %d\n",x3, 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) %d = %d\n", x1, y1); show_bytes(&x1,2); show_bytes(&y1,4); printf("\n\t(int) %d = %d\n", x2, y2); show_bytes(&x2,2); show_bytes(&y2,4); } void casting_demo_signed_unsigned(){ printf("\nCasting 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) %d = %u\n", x1, y1); show_bytes(&x1,4); show_bytes(&y1,4); printf("\n\t(unsigned int) %d = %u\n", x2, 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) %d = %d\n", x1, y1); show_bytes(&x1,4); show_bytes(&y1,4); printf("\n\t(int) %d = %u\n", x2, y2); show_bytes(&x2,4); show_bytes(&y2,4); } void casting_demo(){ casting_demo_shorter(); casting_demo_longer(); casting_demo_signed_unsigned(); casting_demo_unsigned_signed(); } void why_unsigned_is_dangerous(){ int a[8] = {0,1,2,3,4,5,6,7}; for(unsigned int i = 6; 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 = 23; char x; printf("%d = 0x%hhx\n", a, a); printf("%d = 0x%hhx\n", b, b); x = ~a; printf("~(-30) = %d (0x%hhx)\n", x, x); x = a & b; printf("-30 & 23 = %d (0x%hhx)\n", x, x); x = a && b; printf("-30 && 23 = %d (0x%hhx)\n", x, x); x = a >> 2; printf("-30 >> 2 = %d (0x%hhx)\n", x, x); } int main(int argc, char ** argv){ //exercise1(); //casting_demo(); //why_unsigned_is_dangerous(); exercise3(); return 0; }