C++写十进制整数转换二进制数

十进制转换:
将任一整数转换为二进制形式。

#include <iostream>

using namespace std;

void printb(int,int);

void main()
{
    int x;
    cout <<"Input number:";
    cin >>x;
    cout <<"number of decimal form:" <<x <<endl;
    cout <<"    it's binary form:";
    printb(x,sizeof(int)*8);    /* x:整数    sizeof(int):int型在内存所占的字节数,
                                sizeof(int)*8:int型对应的数 */
    cout <<endl;
}

void printb(int x,int n)
{
    if(n>0)
    {
        putchar('0'+((unsigned)(x&(1 << (n-1))) >> (n-1)));    // 输出第n位
        printb(x,n-1);    // 递归调用,输出x的后n-1位
    }
}

posted @ 2012-01-30 22:59  cmaaa  阅读(1133)  评论(0编辑  收藏  举报