FalkoG said:
Hello colleague
I want to convert a floating number for example 5236.9856982 to a
hexadecimal number.
I'd tried several things but my problem is to convert the position
after decimal point. I searched numberless websites but nothing could
numerous
answer my question.
I would be pleased to get some help.
On the assumption that you are asking about representation for humans,
rather than being confused about internal forms,
#include <stdio.h>
#include <float.h>
#include <limits.h>
#include <math.h>
int showhex(double x);
int showoct(double x);
int main(void)
{
double q = 5236.9856982;
/* check to see if your compiler supports the 'a' or 'A' specifier
with printf */
printf("The number represented as %.*g base 10 can be shown as\n",
DBL_DIG, q);
showhex(q);
printf("or\n");
showoct(q);
return 0;
}
/* The following showhex and showoct work over a restricted range of
values. If you need a larger range, handle the integer part
better. While doing that, generalize them to a single function
taking a base in the range 2-36 as in strtoul */
int showhex(double x)
{
double fracp, intp;
int y;
if (x < 0) {
x = -x;
putchar('-');
}
fracp = modf(x, &intp);
if (x > ULLONG_MAX) {
printf("(Number too large.\n");
return 1;
}
printf("%llx.", (unsigned long long) intp);
while (fracp) {
fracp *= 16;
y = fracp;
printf("%x", y);
fracp -= y;
}
printf(" hex\n");
return 0;
}
int showoct(double x)
{
double fracp, intp;
int y;
if (x < 0) {
x = -x;
putchar('-');
}
fracp = modf(x, &intp);
if (x > ULLONG_MAX) {
printf("(Number too large.\n");
return 1;
}
printf("%llo.", (unsigned long long) intp);
while (fracp) {
fracp *= 8;
y = fracp;
printf("%o", y);
fracp -= y;
}
printf(" octal\n");
return 0;
}
The number represented as 5236.9856982 base 10 can be shown as
1474.fc56b79cba hex
or
12164.7705326747135 octal