简体   繁体   中英

How to display the encoding of a floating-point value

How can we print the encoding of a floating-point value in C? I know I can use %A , but that isn't the format I want.

For example, if my value is 1.3416407, I want to print ”0x3FABBAE2“, I do not “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

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. It also matches the sizeof(ui) should it differ from sizeof(int).

Though it does suffer should from the uncommon sizeof(float) != 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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