1. 程式人生 > >c/c++程式碼 No.6 開啟位

c/c++程式碼 No.6 開啟位

#include <iostream>
#include <cstring>
#include <iomanip> 

using namespace std;

char* getBit(unsigned char n) {
    char *str = new char[101];
    int i = 0;
    while (n != 0) {
        str[i++] = n % 2 + '0';
        n /= 2;
    }
    str[i] = '\0';
    strrev(str); 
    return str;
}

char
toBit(char *str) { char n = 0; for (int i = 0; str[i] != '\0'; i++) { n *= 2; n += str[i] - '0'; } return n; } int main(void) { char a = 2; char b = 13; cout << "a:" << endl; char *str = getBit(a); cout << "二進位制" << setfill('0'
) << setw(8) << str << endl; cout << "十進位制" << (int)toBit(str) << endl; delete str; cout << "b:" << endl; str = getBit(b); cout << "二進位制" << setfill('0') << setw(8) << str << endl; cout << "十進位制"
<< (int)toBit(str) << endl; delete str; cout << "a | b" << endl; str = getBit(a | b); cout << "二進位制" << setfill('0') << setw(8) << str << endl; cout << "十進位制" << (int)toBit(str) << endl; delete str; return 0; }