简体   繁体   English

如何显示浮点值的编码

[英]How to display the encoding of a floating-point value

How can we print the encoding of a floating-point value in C? 我们如何在C中打印浮点值的编码? I know I can use %A , but that isn't the format I want. 我知道我可以使用%A ,但这不是我想要的格式。

For example, if my value is 1.3416407, I want to print ”0x3FABBAE2“, I do not “0X1.5775C4P+0”. 例如,如果我的值是1.3416407,我想打印“0x3FABBAE2”,我不是“0X1.5775C4P + 0”。

You can use a union, eg 你可以使用联盟,例如

#include <stdio.h>
#include <stdint.h>

union {
    float f;
    uint32_t i;
} u;

u.f = 1.3416407f;
printf("%#X\n", u.i);

The union idea present by @Paul R is good but would benefit with refinements @Paul R提出的工会理念很好,但会受益于改进

union {
    float f;
    uint32_t i;
} u;

u.f = 1.3416407f;
printf("0x%08" PRIX32 "\n", u.i);

This insures 8 hexadecimal characters are printed, zero padding as needed. 这确保打印8个十六进制字符,根据需要填充零。 It also matches the sizeof(ui) should it differ from sizeof(int). 如果它与sizeof(int)不同,它也匹配sizeof(ui)。

Though it does suffer should from the uncommon sizeof(float) != sizeof(uint32_t); 虽然它确实应该受到不常见的sizeof(浮动)!= sizeof(uint32_t);

You can walk the type octet by octet: 您可以通过八位字节遍历八位字节:

float f = 1.3416407;
unsigned char *fp = (void *)&f;
size_t i;
printf("0x");
for (i = 0; i < sizeof(float); ++i) {
    printf("%02X", fp[i]);
}
puts("");

You may need to print the octets in reverse order depending on the desired endianess. 您可能需要根据所需的字节顺序以相反的顺序打印八位字节。

To print the hexadecimal presentation of an arbitrary thing, use 要打印任意事物的十六进制表示,请使用

union {
    arbitrary object;
    unsigned char bytes[sizeof (arbitrary)];
} u;

Ie

union {
    float object;
    unsigned char bytes[sizeof (float)];
} u;

u.object = 1.3416407f;
printf("0x");
for (size_t i = 0; i < sizeof(u.bytes); i++) {
    printf("%02hhx", u.bytes[i]);
}
printf("\n");

Or to reverse the bytes for little endian: 或者反转小端的字节:

printf("0x");
for (size_t i = sizeof(u.bytes) - 1; i < sizeof(u.bytes); i--) {
    printf("%02hhx", u.bytes[i]);
}
printf("\n");

The code above assumes that CHAR_BIT == 8 . 上面的代码假设CHAR_BIT == 8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM