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.
The length of a double is 64 bits or 8 bytes. Doubles are encoded using the IEEE standard for normalized double-precision floating-point numbers.
Float is a datatype which is used to represent the floating point numbers. It is a 32-bit IEEE 754 single precision floating point number ( 1-bit for the sign, 8-bit for exponent, 23*-bit for the value. It has 6 decimal digits of precision.
The 'int pointer' size can be changed to 64 bits on 64 bits machines, since the memory address size is 64 bits. That means your 'argument' isn't valid. A float is then still a float too: usually we say it is 32 bits, but everyone is free to deviate from it.
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++.
An improvement on the other answers (which assume a char is 8-bits, the standard does not guarantee this..). Would be like this:
char a[sizeof(double) * CHAR_BIT == 64];
or
BOOST_STATIC_ASSERT(sizeof(double) * CHAR_BIT == 64);
You can find CHAR_BIT defined in <limits.h>
or <climits>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With