输出二进制形式
不需要用数组,仅供参考。
复制内容到剪贴板代码:
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "input n:";
cin >> n;
for(int i=1; i<=32; i++){
cout << (n<0?1:0) << (i%8==0?" ":"");
n = n<<1;
}
cout << endl;
}
template<typename T>
void Bits(T const& e)
{
int n(sizeof(T));
char* ch=(char*)&e;
for(int i(n-1),j;i>=0;--i)
{
for(j=7;j>=0;--j)
ch[i]&(char(1)<<j) ? std::cout<<1 : std::cout<<0;
std::cout<<' ';
}
std::cout<<"\n";
}
int main()
{
float a=3.14;
double d=6.28;
Bits(a);
Bits(d);
return 0;
}
http://blog.csdn.net/rainharder/archive/2008/03/10/2164388.aspx
打印二进制的代码也不是那么容易的,不信写个看看,和下面这个(一本老外的C语言教材上的代码)比较一下,看看写的是否全面
c++就简单多了
cout << bitset<numberic_limits<unsigned int>::digits>(123) << endl;
// 还可以把二进制字符串转换为整数
cout << bitset<100>(string("100010110")).to_ulong() << endl;