Question: Hi! I asked for a code in c programming for the following problem: Create a program that outputs the IEEE 754 double-precision binary representation for
Hi!
I asked for a code in c programming for the following problem:
Create a program that outputs the IEEE 754 double-precision binary representation for a passed floating-point number. The floating point number is passed as a command line parameter, where a valid floating point number has the following parts: (1) optional plus or minus sign (2) a non-empty sequence of decimal digits which optionally contains a decimal point (3) optionally an e or E with an optional plus or minus sign and a non-empty sequence of decimal digits.
The user passes a floating point number as command line parameter. (1) If no parameter is passed, the program prints the text "usage: ./s09e02
The text "Number:
The sign (sign), exponent (exponent) and mantissa (mantissa) components of the floating point number are calculated and output in the format "
The text "sign exponent mantissa " is printed on the standard output.
The program is terminated with EXIT_SUCCESS.
Tip:
You can use a union consisting of a double and a uint64_t component to get the bit representation of a double precision floating point number.
The strtod function can be helpful in converting the passed parameter.
Keep exactly to the format of the examples and do not output any additional text!
The output should look like this:
./s09e02 4.1 Number: 4.100000e+00 Binary representation: 0 10000000001 0000011001100110011001100110011001100110011001100110 sign exponent mantissa
As a result I got this code from an expert. The code does not show the exponent and the mantissa in binary representation. How can I integrate this?
#include
#include
#include
#include
#include
#define ERROR_MSG_LEN 100
union double_to_uint64 {
double d;
uint64_t u;
};
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "usage: %s
return EXIT_FAILURE;
}
char *endptr;
double number = strtod(argv[1], &endptr);
if (argv[1] == endptr || strlen(endptr) > 0) {
char error_msg[ERROR_MSG_LEN];
snprintf(error_msg, ERROR_MSG_LEN, "ERROR: %s is not a valid double! Extracted double component: %.6f Remaining: %s",
argv[1], number, endptr);
fprintf(stderr, "%s ", error_msg);
return EXIT_FAILURE;
}
union double_to_uint64 du;
du.d = number;
uint64_t bits = du.u;
printf("Number: %.6e Binary representation: ", number);
int sign = (bits >> 63) & 1;
printf(" %d", sign);
int exponent = (bits >> 52) & ((1ull << 11) - 1);
printf(" %11d", exponent);
uint64_t mantissa = bits & ((1ull << 52) - 1);
printf(" %0*llu ", 52, mantissa);
return EXIT_SUCCESS;
}
Thank you for your help!
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
