因此,我知道 stdint.h
header 中的类型提供了标准化宽度整数类型,但是我想知道人们使用什么类型或方法来保证 double 的大小
或跨平台的其他浮点类型?具体来说,这将处理 void*
#include <stdio.h>
#include <stdlib.h>
void write_double(void* buf, double num)
{
*(double*)buf = num;
}
double read_double(void* buf)
{
return *(double*)buf;
}
int main(void) {
void* buffer = malloc(sizeof(double));
write_double(buffer, 55);
printf("The double is %f\n", read_double(buffer));
return 0;
}
比如在上面的程序中,如果我将那个 void*
写入一个文件,或者如果它被用在另一个系统上,是否有一些标准的方法来保证浮点类型的大小或者双?
最佳答案
How to guarantee exact size of double in C?
使用_Static_assert()
#include <limits.h>
int main(void) {
_Static_assert(sizeof (double)*CHAR_BIT == 64, "Unexpected double size");
return 0;
}
_Static_assert
从 C11 开始可用。否则代码可以使用运行时断言。
#include <assert.h>
#include <limits.h>
int main(void) {
assert(sizeof (double)*CHAR_BIT == 64);
return 0;
}
虽然这将确保 double
的大小为 64,但它不能确保 IEEE 754 double-precision binary floating-point format坚持。
代码可以使用__STDC_IEC_559__
An implementation that defines
__STDC_IEC_559__
shall conform to the specifications in this annex` C11 Annex F IEC 60559 floating-point arithmetic
但这可能太严格了。许多实现都遵循该标准的大部分内容,但仍未设置宏。
would there be some standard way to guarantee size of a floating point type or double?
最好的保证是将 FP 值写入其十六进制表示形式或具有足够小数位的指数形式。参见 Printf width specifier to maintain precision of floating-point value
关于c - 如何保证 C 中 double 的确切大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47187604/