Ensuring C++ doubles are 64 bits

Whatsit picture Whatsit · Apr 15, 2009 · Viewed 12.6k times · Source

In my C++ program, I need to pull a 64 bit float from an external byte sequence. Is there some way to ensure, at compile-time, that doubles are 64 bits? Is there some other type I should use to store the data instead?

Edit: If you're reading this and actually looking for a way to ensure storage in the IEEE 754 format, have a look at Adam Rosenfield's answer below.

Answer

Adam Rosenfield picture Adam Rosenfield · Apr 15, 2009

In C99, you can just check if the preprocessor symbol __STDC_IEC_559__ is defined. If it is, then you are guaranteed that a double will be an 8-byte value represented with IEEE 754 (also known as IEC 60559) format. See the C99 standard, Annex F. I'm not sure if this symbol is available in C++, though.

#ifndef __STDC_IEC_559__
#error "Requires IEEE 754 floating point!"
#endif

Alternatively, you can check the predefined constants __DBL_DIG__ (should be 15), __DBL_MANT_DIG__ (should be 53), __DBL_MAX_10_EXP__ (should be 308), __DBL_MAX_EXP__ (should be 1024), __DBL_MIN_10_EXP__ (should be -307), and __DBL_MIN_EXP__ (should be -1021). These should be available in all flavors of C and C++.