但输入一个数字时,怎么样转换成二进制数,用C++实现

p0303230 2010-05-26 02:22:20
但输入一个数字时,怎么样转换成二进制数,用C++实现


写出代码

谢谢
...全文
505 12 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
gz_qmc 2010-05-27
  • 打赏
  • 举报
回复
这个鸡巴鸟论坛,老是自动删除我的空格
gz_qmc 2010-05-27
  • 打赏
  • 举报
回复
//#include "string.h"
//
//void ToBit(long x,char *bin,long len)
//{
// union
// {
// long num;
// unsigned v:1;
// }b;
// char *temp=new char[32];
// memset(temp,0x30,32);
// int pos=32;
// while(pos--)
// {
// b.num=x;
// temp[pos]+=b.v;
// x>>=1;
// }
// int max=len<33?len:33;
// memcpy(bin,temp,max);
// delete temp;
//}


//void main()
//{
// long x=2;
// char buf[33]={0};
// ToBit(x,buf,32);
// printf("%s\n\n",buf);
//}
gz_qmc 2010-05-27
  • 打赏
  • 举报
回复
#include "string.h"

void ToBit(long x,char *bin,long len)
{
union
{
long num;
unsigned v:1;
}b;
char *temp=new char[32];
memset(temp,0x30,32);
int pos=32;
while(pos--)
{
b.num=x;
temp[pos]+=b.v;
x>>=1;
}
int max=len<33?len:33;
memcpy(bin,temp,max);
delete temp;
}


void main()
{
long x=2;
char buf[33]={0};
ToBit(x,buf,32);
printf("%s\n\n",buf);
}
  • 打赏
  • 举报
回复
上面打字打错了,最简单的就是用bitset,呵呵。
p0303230 2010-05-26
  • 打赏
  • 举报
回复
谢谢各位啦
  • 打赏
  • 举报
回复
楼上的方法都行,最简单的就是用不用bitset,下面是我提供的一种方法:

#include <iostream>
using namespace std;

int main()
{
int i;
int array[32];

cin >> i;

for (int j = 31; j != -1; --j)
{
array[j] = i & 1;
i = i >> 1;
}

j = 0;

while(array[j] == 0)
{
++j;
}

for ( ; j!= 32; ++j)
{
cout << array[j];
}

cout << endl;


return 0;
}
mskmc_mc 2010-05-26
  • 打赏
  • 举报
回复
支持C++标准库的bitset
beginsoft_nj 2010-05-26
  • 打赏
  • 举报
回复
char *_itoa( int value, char *string, int radix );
liutengfeigo 2010-05-26
  • 打赏
  • 举报
回复
直接控制输出格式???
  • 打赏
  • 举报
回复
。。。。。。。。。。。。。。。。。。。。
gykgod 2010-05-26
  • 打赏
  • 举报
回复
嘿嘿,我的垃圾代码

#include <iostream>
using namespace std;
int main()
{
int a=0;
int i=0;
int j=0;
int stack[1024] = {0};
int count = 0;

cin >> a;

while (a !=0)
{

i = a/2;
j = a%2;
a = a/2;
count ++;
stack[count-1] = j;

}
while(count!=0)
{
cout << stack[count-1];
count--;
}
return 0;
}
selooloo 2010-05-26
  • 打赏
  • 举报
回复
简单点用bitset
#include <iostream>
#include <bitset>
using namespace std;

int main(void)
{
int n;
bitset<32> nb;

cin>>n;
nb=n;
cout<<nb<<endl;
system("pause");
return 0;
}

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧