C++ 如何以二进制输出int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3269767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to output an int in binary?
提问by user299648
int x = 5;
cout<<(char)x;
the code above outputs an int x in raw binary, but only 1 byte. what I need it to do is output the x as 4-bytes in binary, because in my code, x can be anywhere between 0 and 2^32-1, since
上面的代码以原始二进制格式输出一个 int x,但只有 1 个字节。我需要它做的是将 x 输出为 4 字节的二进制,因为在我的代码中,x 可以在 0 到 2^32-1 之间的任何位置,因为
cout<<(int)x;
doesn't do the trick, how would I do it?
不成功,我该怎么做?
采纳答案by James McNellis
You can use the std::ostream::write()
member function:
您可以使用std::ostream::write()
成员函数:
std::cout.write(reinterpret_cast<const char*>(&x), sizeof x);
Note that you would usually want to do this with a stream that has been opened in binary mode.
请注意,您通常希望对以二进制模式打开的流执行此操作。
回答by Johann Horvat
A bit late, but, as Katy shows in her blog, this might be an elegant solution:
有点晚了,但是,正如 Katy 在她的博客中展示的那样,这可能是一个优雅的解决方案:
#include <bitset>
#include <iostream>
int main(){
int x=5;
std::cout<<std::bitset<32>(x)<<std::endl;
}
taken from: https://katyscode.wordpress.com/2012/05/12/printing-numbers-in-binary-format-in-c/
取自:https: //katyscode.wordpress.com/2012/05/12/printing-numbers-in-binary-format-in-c/
回答by Martin York
Try:
尝试:
int x = 5;
std::cout.write(reinterpret_cast<const char*>(&x),sizeof(x));
Note: That writting data in binary format is non portable.
If you want to read it on an alternative machine you need to either have exactly the same architecture or you need to standardise the format and make sure all machines use the standard format.
注意:以二进制格式写入数据是不可移植的。
如果您想在另一台机器上阅读它,您需要具有完全相同的架构,或者您需要标准化格式并确保所有机器都使用标准格式。
If you want to write binary the easiest way to standardise the format is to convert data to network format (there is a set of functions for that htonl() <--> ntohl() etc)
如果要编写二进制文件,最简单的标准化格式的方法是将数据转换为网络格式(有一组函数用于 htonl() <--> ntohl() 等)
int x = 5;
u_long transport = htonl(x);
std::cout.write(reinterpret_cast<const char*>(&transport), sizeof(u_long));
But the most transportable format is to just convert to text.
但最易传输的格式是仅转换为文本。
std::cout << x;
回答by KikoV
and what about this?
这个呢?
int x = 5;
cout<<(char) ((0xff000000 & x) >> 24);
cout<<(char) ((0x00ff0000 & x) >> 16);
cout<<(char) ((0x0000ff00 & x) >> 8);
cout<<(char) (0x000000ff & x);
回答by John
A couple of hints.
一些提示。
First, to be between 0 and 2^32 - 1 you'll need an unsignedfour-byte int.
首先,要介于 0 和 2^32 - 1 之间,您需要一个无符号的四字节 int。
Second, the four bytes starting at the address of x (&x) already have the bytes you want.
其次,从 x (&x) 的地址开始的四个字节已经有了你想要的字节。
Does that help?
这有帮助吗?