二进制的打印

下面是摘抄网友的的代码

void fun(int i, char *res){
    int j = 0;
    while(i){
        *(res + j) = i % 2 + '0';
        i /= 2;
        ++j;
    }
    *(res + j) = '\0';
    strrev(res);
}

这个感觉太冗长了。

而后是这个:

#include <iostream>
#include <bitset>
#include <string>

void printBinary(int n) {
    std::bitset<32> bits(n);
    for (int i = bits.size() - 1; i >= 0; --i) {
        std::cout << bits[i];
    }
    std::cout << std::endl;
}

  感觉还比较简洁的c++代码

 

 

#include<iostream>
#include<bitset>

using namespace std;

void two(int x)
{
    bitset<32> two(x);
    for(int len=two.size()-1;len>=0;--len)
        cout<<two[len];
    cout<<endl;
}

  这个是我看到的非常好的二进制显示代码。。

不过,最后我要的是推荐我更欣赏的代码,

而且是c的。。哈哈

void binary_(int x)
{
    if (x<=0) return;
    else
    {            
        binary_(x/2);
        printf("%d",x%2);
    }
}

很好好强大,,

使用递归实现的。

我确实拜服。。

以后要多多用递归。。

哈哈。

posted on 2012-09-03 13:35  hcu5555  阅读(322)  评论(0编辑  收藏  举报