It is possible to access to the bit representation of a floating point constant in C;
For example i'd like to assign
uint64_t x = //bit representation of 5.74;
which is represented by 0x40b7ae14
Do you think it is possible?
One way of achieving this is to use a union:
union {
double fltValue;
uint64_t uintValue;
} conversion;
conversion.fltValue = 5.74;
printf("%#llx\n", conversion.uintValue);
Updated with %#x
thanks to Aracthor for mentioning it. And %#llx
thanks to EOF.
For a working example (with float
instead of double
) see:
It is possible, but is not portable because you cannot be sure of how a floating point value is represented : C standard does not define it.
You could simply use casting of pointers :
float x = 5.74;
void *pt = &x
uint64_t *ip = pt;
uint64_t i = *ip;
This is formal undefined behaviour because you are casting a pointer to a different type, and you should not do it because you add endian problems to the floating point representation.
The correct way would be :
float x = 5.74;
void *pt = &x
unsigned char *ip = pt;
ip
now point to a unsigned char[]
of size sizeof(float)
containing the binary representation of a float. And no undefined behaviour was invoked because casting a pointer to a void *
or a char *
is always allowed.
#include <stdint.h>
#include <stdio.h>
int main(void) {
double x = 5.74;
uint64_t y = *((uint64_t*)&x);
printf("0x%016llx", y); /* 0x4016f5c28f5c28f6 */
}
如果要使用浮点数的二进制表示形式,请使用整数指针..将float变量的地址分配给整数指针,并通过取消引用int指针的值来获取其二进制形式。某种程度上想要避免由异常类型转换产生的警告,那么您可以始终使用void *
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.