#include // This code shows // the "boolean" in C (ints really) // how the same bit pattern can have different meanings // by looking at these bits through differently typed pointers // endianness, // printf formats and types // two static variables char a[4] = {'A','B','C','D'}; int one = 1; int isBigE(){ // see int 1 as chars, get the first char, // if it is zero, the machine is big endian // this following expression // 1. gets the address of the static variable one: &one // 2. casts it to an char pointer: (char *) // 3. dereferences it to a char: * // now we have the first byte of one // this is a standard trick to cast one type into another // can you do that in Java? return!(*((char*)(&one))); } int main(){ char* c = a; // c sees a as chars, points at first byte of a short* s = (short*)a; // s sees a as shorts, points at first short int* p = (int*)a; // p sees a as int, points at it float* f = (float*)a; // f sees a as float, points at it int* p1 = &one; // p1 points at int one char* c1 = (char*)p1; // c1 points at first char of one printf("sizeof(int) = %d\n", (int) sizeof(int)); printf("sizeof(long) = %d\n", (int) sizeof(int)); printf("sizeof(long long) = %d\n", (int) sizeof(long long)); printf("sizeof(int*) = %d\n",(int) sizeof(int*)); // booleans are represented by ints in C if(0) printf("zero = true\n"); else printf("zero = false\n"); if(1) printf("one = true\n"); else printf("one = false\n"); if(-1) printf("-1 = true\n"); else printf("-1 = false\n"); if(5) printf("non-zero = true\n"); else printf("non-zero = false\n"); // check the endianness of the machine executing this code if(isBigE()) printf("This machine is big endian, first byte of one: %c\n", '0'+*c1); else printf("This machine is little endian, first byte of one: %c\n", '0'+*c1); // this format %x prints in hex printf("45 in hex: %x\n", 45); float coolfloat = -8346975.000000f; // The %x format doesn't work for floats printf("-8346975.000000 in hex: %x\n", coolfloat); // We can try a static cast but we still get the wrong answer printf("-8346975.000000 in hex (try #2): %x\n", (int)coolfloat); // print a through the eyes of differently typed pointers printf("a as four chars using a[i] : %c %c %c %c\n", a[0], a[1], a[2], a[3]); printf("a as four chars using char*: %c %c %c %c\n", *c, *(c+1), *(c+2), *(c+3)); printf("a as two shorts: %d %d\n", *s, *(s+1)); printf("char %c in hex: %x\n", a[0], a[0]); printf("a as int: %d, that's in hex: %x, revealing machine endianness\n", *p, *p); printf("a as a float: %f\n", *f); // Now we know the correct way to print a float as hex printf("-8346975.000000 in hex (correct way): %x\n", *((int*)(&coolfloat))); return 0; }