Search
The exercise will be based on following C code. It prints number representation in computer memory. We shall modify the code during the class.
#include <stdio.h> #define PRINT_MEM(a) print_mem((unsigned char*)&(a), sizeof(a)) void print_mem(unsigned char *ptr, int size) { int i; printf("address = 0x%08lx\n", (long unsigned int)ptr); for (i = 0; i < size; i++) { printf("0x%02x ", *(ptr+i)); } printf("\n"); } int main() { unsigned int unsig = 5; int sig = -5; printf("value = %d\n", unsig); PRINT_MEM(unsig); printf("\nvalue = %d\n", sig); PRINT_MEM(sig); return 0; }
Python language alternative
#!/usr/bin/python3 import struct a = 1234.56789 b = -11.1111111111111111111111 c = a + b buf = struct.pack('<f', c) print ('C float LE:' + ' '.join(["{0:02x}".format(b) for b in buf])) print ('C float LE:' + str(struct.unpack('<f', buf)[0])) buf = struct.pack('>f', c) print ('C float BE:' + ' '.join(["{0:02x}".format(b) for b in buf])) print ('C float BE:' + str(struct.unpack('>f', buf)[0])) buf = struct.pack('<d', c) print ('C double LE:' + ' '.join(["{0:02x}".format(b) for b in buf])) print ('C double LE:' + str(struct.unpack('<d', buf)[0])) buf = struct.pack('>d', c) print ('C double BE:' + ' '.join(["{0:02x}".format(b) for b in buf])) print ('C double BE:' + str(struct.unpack('>d', buf)[0]))
See Python struct module for more struct — Interpret bytes as packed binary data.