只需一步,快速开始
想知道怎样输出二进制。我们知道C++输出十六进制是cout〈〈hex〈〈 a;而八进制是cout〈〈 ocx〈〈 a;二进制则没有默认的输出格式,需要自己写函数进行转换,于是上网搜索了一下。网上思路真是广泛啊。下面列出一些方法。
#include 〈iostream〉
#include 〈list〉
#include 〈bitset〉
using namespace std;
//递归输出二进制函数
void BinaryRecursion(int n) { int a; a=n%2; n=n〉〉1; if (n==0) ; else BinaryRecursion(n); cout〈〈a; } 复制代码
使用道具 举报
//使用容器转换二进制
void BinaryVector(int n) { int temp; temp=n; list〈int〉 L; while(temp!=0) { L.push_front(temp%2); temp=temp〉〉1; } for (list〈int〉::iterator iter=L.begin();iter!=L.end();iter++ ) cout〈〈*iter; cout〈〈endl; } 复制代码
从中可以看出,有两种运算会得出32位的结果,不太好。对C++还不是很精通,所以这个效率还不是很清楚哪个个好。觉得用容器的可能会好些吧。如果是C,就用字符转换函数,或者直接除后和1做与运算。
#include<stdio.h> void printb(int,int); int main() { int x; printf("Input number:"); scanf("%d",&x); printb(x,sizeof(int)*8); putchar('\n'); return 0; } void printb(int x,int n) { if(n>0) { putchar('0'+((unsigned)(x&(1<<(n-1)))>>(n-1))); printb(x,n-1); } }复制代码
本版积分规则 发表回复 回帖并转播 回帖后跳转到最后一页
|Archiver|手机版|小黑屋|爱乐眼底图像分析 ( 京ICP备12011552号-2 )
GMT+8, 2026-11-21 05:03 , Processed in 0.095690 second(s), 19 queries .
Powered by Discuz! X3.5
© 2001-2026 Discuz! Team.