二进制的打印

下面是摘抄网友的的代码

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);
    }
}

很好好强大,,

使用递归实现的。

我确实拜服。。

以后要多多用递归。。

哈哈。


作者:issta hu
出处:http://www.cnblogs.com/hcu5555/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/hcu5555/p/2668661.html