如何输出二进制一个int? [英] how to output an int in binary?

查看:143
本文介绍了如何输出二进制一个int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int x = 5;
cout<<(char)x;

以上code在输出原始的二进制一个int x,但只有1个字节。我需要做的是输出x作为二进制的4个字节,因为在我的code,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

cout<<(int)x;

不会做的伎俩,我会怎么做呢?

doesn't do the trick, how would I do it?

推荐答案

您可以使用的std :: ostream的::写()成员函数:

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.

这篇关于如何输出二进制一个int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆