// needed for library function printf() #include /* Normally you would put function prototypes here: void show_bytes(char *start, int len); void show_int(int x); Except that in this case the function declarations come before their first calls in the file, so they are not necessary. */ /* Takes start address of data and prints out len bytes in hex. */ void show_bytes(char *start, int len) { unsigned int i; // for loop doesn't need curly braces {} because single-line body for (i = 0; i < len; i++) // printf symbols: // %p - print as pointer // \t - tab character // %x - print in hex (.2 means pad to 2 digits) // \n - newline character printf("%p\t%#02x\n", start + i, (unsigned char)*(start + i)); printf("\n"); } /* Uses show_bytes() to print hex representation of integer. Use of sizeof() means this code will work even if int isn't 4B. */ void show_int(int x) { show_bytes((char *)&x, sizeof(int)); unsigned int bytes = 0; unsigned int mask = 0xff; while (bytes <= 3) { unsigned char value = x & mask; printf("x = %x, mask = %x, x&mask = %x", x, mask, value); // value = value >> (bytes * 8); printf("\n Byte %d = 0x%.2x\n", bytes, value); bytes++; x = (unsigned int)x >> 8; // mask = mask << 8; } } /* Example usage of show_int(). */ int main() { int x = 0xdeadbeef; // 12345 = 0x3039 printf("int x = %d (0x%x);\n", x, x); show_int(x); return 0; }