Col*_*son 0 c c++ floating-point unions
我得到了一个浮点变量,想知道它的字节表示是什么.所以我去IDEOne 写了一个简单的程序来做到这一点.但是,令我惊讶的是,它会导致运行时错误:
#include <stdio.h>
#include <assert.h>
int main()
{
// These are their sizes here. So just to prove it.
assert(sizeof(char) == 1);
assert(sizeof(short) == 2);
assert(sizeof(float) == 4);
// Little endian
union {
short s;
char c[2];
} endian;
endian.s = 0x00FF; // would be stored as FF 00 on little
assert((char)endian.c[0] == (char)0xFF);
assert((char)endian.c[1] == (char)0x00);
union {
float f;
char c[4];
} var;
var.f = 0.0003401360590942204;
printf("%x %x %x %x", var.c[3], var.c[2], var.c[1], var.c[0]); // little endian
}
Run Code Online (Sandbox Code Playgroud)
在IDEOne上,它输出:
39 ffffffb2 54 4a
以及运行时错误.为什么会出现运行错误,为什么是b2实际ffffffb2?我的猜测b2是符号扩展.
小智 6
char是签名类型.如果它是8位长并且你在其中放入大于127的任何东西,它将溢出.有符号整数溢出是未定义的行为,因此使用转换说明符打印带符号的值,该转换说明符需要无符号的(%x期望unsigned int,但在传递给可变参数函数时char被提升[隐式转换] ).signed intprintf()
底线 - 更改char c[4]为unsigned char c[4],它将正常工作.