hi, i wrote the following program to print out the contents of the memory of a variable. to handle different types, i have used macros definition combined with a void pointer...
Code:
#include<stdio.h>
#include<stdlib.h>
#define type_scan(type, type_specifier) a_number = (type *)malloc(sizeof(type));\
scanf(#type_specifier, (type *)a_number);\
segment = sizeof(type) * 8;
int main()
{
void *a_number;
int segment;
int choice;
unsigned char *byte;
char memory[1024];
int i, j;
printf("Enter type (i - int, f - float, l - long, u - unsigned int, d - double) : ");
choice = getchar();
printf("Enter any number: ");
switch(choice) {
case 'i':
type_scan(int, %d);
break;
case 'f':
type_scan(float, %f);
break;
case 'l':
type_scan(long, %D);
break;
case 'u':
type_scan(unsigned int, %u);
break;
case 'd':
type_scan(double, %g);
break;
}
j = i = 0;
byte = (unsigned char *)a_number;
while(j < segment) {
for(i = 0; i < 8; i++) {
memory[j++] = ((*byte & (1 << i)) > 0) ? '1' : '0';
}
byte++;
}
while(j--) {
printf("%c", memory[j]);
if((j % 8) == 0) printf(" ");
}
printf("\n");
exit(0);
}
the output works for int type, for eg,
Code:
Enter type (i - int, f - float, l - long, u - unsigned int, d - double) : i
Enter any number: 120
00000000 00000000 00000000 01111000
but if a double type input is given, it shows all the high order four bytes (double being 8 bytes long) = 0 irrespective of input.
why?? and is this even right way to print out the memory??