c - 如何保证 C 中 double 的确切大小?

标签 c

因此,我知道 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/

相关文章:

c - 从 char 响应缓冲区中提取 JSON 文本

c++ - 与库的 c 绑定(bind)链接

c - 为什么我的 rgb 到 uint32 预处理器宏给我错误的颜色代码?

c - 如何在c中打印字符串末尾没有p┐的字符串

c - 解释这个程序的输出

c - "function strupr not declared on this scope"

c - SSL 例程 :SSL3_READ_N:read bio not set

c - 如何在 Linux 中从用户空间找到变量的物理地址?

c - Win32 C/C++ 桌面应用程序中的 Google Maps Api 集成

文本到二进制转换器的类型冲突?