*** 自写代码:将十进制数以二进制和十六进制形式输出

#include <iostream>
#include <sstream>
using namespace std;
void printBit (unsigned int value)
{
    unsigned int bits = sizeof(unsigned int) * 8;
    stringstream s;
    for (int i=0; i<bits; i++)
    {
        unsigned int temp;
        temp = value & (1<<bits-1-i);
        temp = temp >> bits-1-i;
        s << (temp)?'1':'0';
    }
    cout << s.str() << endl;
}
void printHex (unsigned int value)
{
    unsigned int bits = sizeof(unsigned int) * 2;
    stringstream s;
    for (int i=0; i<bits; i++)
    {
        unsigned int temp;
        temp = value & (0xf << (bits-1-i)*4);
        temp = temp >> (bits-1-i)*4;
        s << (char)((temp>9)?('a'+temp-10):('0'+temp));
    }
    cout << "0x" << s.str() << endl;
}
int main()
{
    printBit (52);
    printHex (0x465c3b);
    return 0;
}

 

posted @ 2018-12-23 19:15  super行者  阅读(335)  评论(0编辑  收藏  举报