十六进制到长双c++

Hex to long double c++

本文关键字:c++ 十六进制      更新时间:2023-10-16

任何人都知道如何在c++中将长双精度转换为十六进制并从十六进制反转为长双精度。我已经使用istringstream将HEXstring转换为long-long并将其强制转换为double,但不知道如何转换long-long,以及如何测试类似的东西。

如果你真的确定要这样做,你可以最大限度地使用联合来"欺骗类型系统"。显然,这是原始内存访问,并附带了大量注意事项。最重要的是,它只是"通常"工作,但不受语言规范的保证

下面是输出长双精度原始字节的代码。从十六进制字符串重新组装长双精度的代码应该不会太难提供给您自己。

#include <stdio.h>
typedef union {
  long double ld;
  char bytes[sizeof(long double)];
} converter; 
int main() {
  converter c;
  c.ld = 3.49;
  printf("0x");
  for (int i = 0; i < sizeof(long double); ++i) {
    printf("%x", c.bytes[i]);
  }
  printf("n");
}

很抱歉发布死讯。无论如何,这是我的解决方案。它应该在long double是类型的任何平台上工作。

除了位字段外,对象由一个或多个字节的连续序列组成,每个字节由CHAR_bit位组成,并且可以使用memcpy复制到unsigned CHAR[n]类型的对象中,其中n是对象的大小。结果数组的内容称为对象表示。

请参阅:C对象严格别名

// C11
#include <stdio.h>  // printf
#include <string.h> // memcpy, size_t, NULL
#include <assert.h> // assert macro
int main(void) {
  const long double src = 3.1415926L;
  unsigned char dest[sizeof src] = { 0 };
  assert (memcpy(dest, &src, sizeof src) != NULL);
  printf("%Lf in hex: 0x", src);
  for (size_t i = 0ul; i < sizeof src; ++i)
    printf("%X", dest[i]);
}

实例