Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print hexadecimal double in C?

Tags:

c

linux

unix

hex

I have this number in hexadecimal:

FFFFFFFFFFFF

and I need to save it, so I used double

double a=0xffffffffffff;

but I need to print it and I don't know how to. Each time I use %f, %d, %x, it doesn't print the value of it; I just need to print ffffffffffff. My code:

int main()
{
    double a=0xffffffffffff;
    printf("%x\n",a);
    printf("%d\n",a);
    printf("%X\n",a);
    printf("%f\n",a);
    return 0;
}

The only true value is %f; that returns the decimal value of the hexadecimal — it returns this:

 ffffffe0
 -32 
 FFFFFFE0
 281474976710655.000000

with this I need to change from that hexadecimal to string, to compare it, because I have FFFFFFFFFFFF in string too and I need to compare both. If I can't printf it, neither will sprintf will work.

like image 202
Luis Daniel Rubiera Avatar asked May 08 '13 13:05

Luis Daniel Rubiera


People also ask

How do I print a hex character?

Here's a solution: char ch = 0xC0; printf("%x", ch & 0xff);

What is used for printing double in C?

We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.

Can print long double in C?

We can print the long double value using %Lf format specifier.

What is hexadecimal in C?

In C programming language, a hexadecimal number is a value having a made up of 16 symbols which have 10 standard numerical systems from 0 to 9 and 6 extra symbols from A to F. In C, the hexadecimal number system is also known as base-16 number system.


1 Answers

That's an integer, and a long one. Don't use double to store such a value, that's for floating-point.

Just use:

unsigned long long temp = 0xffffffffffffull;

You have 12 hexadecimal digits, so your number needs at least 12 * 4 = 48 bits. Most platforms should have an unsigned long long of 64 bits, which should be fine.

If your compiler is supported enough to support C99, you can do:

#include <stdint.h>

and then use the uint_least64_t type as suggested in a comment. In Linux I guess you're using GCC so you should be fine, you might need to specify that you intend your code to be compiled as C99 (with -std=c99).

To print it, use:

printf("temp=%llx\n", temp);

Also note that the value itself is not hexadecimal, but you can print it as hexadecimal. THe value is just a value, the base matters only when converting to/from text, i.e. an external representation of the number. Internally on a binary computer, the number is stored in binary.

like image 66
unwind Avatar answered Sep 19 '22 22:09

unwind