/** * Program to show hexadecimal representation of ints and doubles. * * Attempts to be as portable as possible by using "union" data types * to access data as array of unsigned characters (bytes). * * Also prints sizes of some things (to show how they can be different * on different systems). */ #include typedef union { int n; unsigned char chars[sizeof (int)]; } int_or_char; typedef union { double d; unsigned char chars[sizeof (double)]; } double_or_char; /* * print hexadecimal representation of array of chars * "size_t" here is an unsigned integer type big enough to hold sizes * of things. */ void print_chars_hex(unsigned char* chars, size_t num_chars) { for (size_t i = 0; i < num_chars; ++i) { printf("%.2hhx ", chars[i]); } printf("\n"); } /* * print hexadecimal representation of int */ void print_int_hex(int_or_char* int_data) { printf("int %d in hexadecimal is ", int_data->n); print_chars_hex(int_data->chars, sizeof int_data->n); } /* * print hexadecimal representation of double */ void print_double_hex(double_or_char* double_data) { printf("double %g in hexadecimal is ", double_data->d); print_chars_hex(double_data->chars, sizeof double_data->d); } /* main program */ int main(void) { int_or_char int_data; double_or_char double_data; printf("sizeof int is %zd\n", sizeof(int)); printf("sizeof short is %zd\n", sizeof(short)); printf("sizeof long is %zd\n", sizeof(long)); printf("sizeof size_t is %zd\n", sizeof(size_t)); printf("sizeof float is %zd\n", sizeof(float)); printf("sizeof double is %zd\n", sizeof(double)); printf("\n"); printf("enter floating-point values, anything else to end:\n"); while (scanf("%lg", &(double_data.d)) == 1) { int_data.n = (int) double_data.d; print_int_hex(&int_data); print_double_hex(&double_data); } return 0; }