[英]Binary representation of a double
I was bored and wanted to see what the binary representation of double's looked like. 我很无聊,想看看double的二进制表示是什么样子。 However, I noticed something weird on windows.
但是,我注意到窗户上有些奇怪的东西。 The following lines of codes demonstrate
以下代码行演示
double number = 1;
unsigned long num = *(unsigned long *) &number;
cout << num << endl;
On my Macbook, this gives me a nonzero number. 在我的Macbook上,这给了我一个非零的数字。 On my Windows machine it gives me 0.
在我的Windows计算机上,它给我0。
I was expecting that it would give me a non zero number, since the binary representation of 1.0 as a double should not be all zeros. 我期望它会给我一个非零的数字,因为1.0的二进制表示形式应该不是全为零。 However, I am not really sure if what I am trying to do is well defined behavior.
但是,我不确定我要做的是行为是否明确。
My question is, is the code above just stupid and wrong? 我的问题是,上面的代码只是愚蠢和错误的吗? And, is there a way I can print out the binary representation of a double?
而且,有没有一种方法可以打印出double的二进制表示形式?
Thanks. 谢谢。
1 double is 3ff0 0000 0000 0000
. 1 double是
3ff0 0000 0000 0000
。 long
is a 4 byte int . long
是一个4字节的int 。 On a little endian hardware you're reading the 0000 0000
part. 在小的字节序硬件上,您正在读取
0000 0000
部分。
If your compiler supports it (GCC does) then use a union. 如果您的编译器支持(GCC支持),则使用联合。 This is undefined behavior according to the C++ standard (strict aliasing rule):
根据C ++标准(严格的别名规则),这是未定义的行为:
#include <iostream>
int main() {
union {
unsigned long long num;
double fp;
} pun;
pun.fp = 1.0;
std::cout << std::hex << pun.num << std::endl;
}
The output is 输出是
3ff0000000000000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.