/** * Program to show hexadecimal representation of ints and doubles. * * Attempts to be as portable as possible by copying data to an * array of characters (bytes) and printing representations of bytes. * * Also prints sizes of some things (to show how they can be different * on different systems). */ #include #include /* * 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(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: * copy to array of characters and use print_chars_hex */ void print_int_hex(int n) { char chars[sizeof n]; memcpy(chars, &n, sizeof n); printf("int %d in hexadecimal is ", n); print_chars_hex(chars, sizeof chars); } /* * print hexadecimal representation of double: * copy to array of characters and use print_chars_hex */ void print_double_hex(double d) { char chars[sizeof d]; memcpy(chars, &d, sizeof d); printf("double %g in hexadecimal is ", d); print_chars_hex(chars, sizeof chars); } /* main program */ int main(void) { double d; 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", &d) == 1) { print_int_hex((int) d); print_double_hex(d); } return 0; }