I'm new to C. I was trying to write a script that would take a double
and print the IEEE 754 binary representation. I was able to successfully do it with float
and int
, but I'm not sure why it's not working with double
.
Essentially, my code creates a pointer to the location in memory that the double
is stored, and then a for
loop will &
each bit in that pointer with a mask, where but one of the bits are zero. The for
loop will go through each bit in the pointer and print the value of &
for each bit, which in turn prints the way the double is stored in memory.
At least, in theory. The double
s that are being returned don't match the input.
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
void inputFloat(float n)
{ // start void
int *p; // pointer to n
p = &n;
int i;
for (i = 31; i >= 0; i--)
{ // open for loop
int mask = 1<<i;
int and = *p & mask;
if (and == 0) printf("0");
else printf("1");
} // close for loop
} //end float void
void inputInt(int n)
{ // start void
int *p; // pointer to n
p = &n;
int i;
for (i = 31; i >= 0; i--)
{ // open for loop
int mask = 1<<i;
int and = *p & mask;
if (and == 0) printf("0");
else printf("1");
} // close for loop
} //end int void
/* new */
void inputDouble(double n)
{ // start void
unsigned long long *p; // pointer to n
printf("input= %f\n", n);
p = (unsigned long long *)&n;
int i;
for (i = 63; i >= 0; i--)
{ // open for loop
int shift =i;
unsigned long long mask = 1<<shift;
unsigned long long and =*p & mask;
if (and == 0) printf("0");
else printf("1");
} // close for loop
/* old
void inputDouble(double n)
{ // start void
int *p; // pointer to n
p = &n;
int i;
for (i = 63; i >=0; i--)
{ // open for loop
int mask = 1<<i;
int and = *p & mask;
if (and == 0) printf("0");
else printf("1");
} // close for loop
} //end double void
*/
int main(int argc, char **argv)
{ // open int main
char *pointer;
double dub;
int option;
while ((option = getopt(argc, argv, "f:i:d:")) !=-1)
{ //open while loop
switch (option)
{ // open switch
case 'f' :
inputFloat(atof(optarg));
printf("\nFloat");
break; // end float option
case 'i' :
inputInt(atoi(optarg));
printf("\nInteger");
break;
case 'd' :
dub = strtod(optarg, &pointer);
inputDouble(dub);
printf("\n Double");
break;
default :
printf("Error");
break;
} // end switch
}//end while loop
printf("\n");
return 0;
} // end int main