将十六进制值存储为整数

时间:2019-09-30 23:22:13

标签: c

我正在尝试获取浮点值的十六进制表示形式,到目前为止,我已经能够做到这一点:

float num = 263.3
int hexInt = *(int*)#
printf("%d", hexInt); // some integer value i dont understand
printf("%x", hexInt); //the hexidecimal represenation of num

我很好奇整数hexInt在格式化为整数时代表什么。

2 个答案:

答案 0 :(得分:0)

  

...获取浮点值的十六进制表示形式

只需使用"%a\n"

printf("%a\n", 263.3f);  // May print `0x1.074cccp+8

答案 1 :(得分:0)

要查看编码浮点对象的数据,可以使用:

#include <inttypes.h> // For printf format PRIx32.
#include <stdint.h>   // For uint32_t.
#include <string.h>   // For memcpy.
...
// Copy bytes of float num into bytes of uint32_t x.
uint32_t x;
_Static_assert(sizeof x == sizeof num, "num must be 32 bits."); // Check size.
memcpy(&x, &num, sizeof x);

// Print x as a hexadecimal numeral.
printf("0x%" PRIx32 "\n", x);

x中的值是一个数字。无论是以十六进制还是十进制打印,都将打印相同的值,只是以不同的底数为单位。这不会更改x中的数字。以十六进制打印它对人类来说更有用,使他们能够在显示器中看到浮点格式的组成部分。但是无论以十六进制还是十进制显示,该值都是相同的。

相关问题