c/c++代码 No.2 位与

#include 
#include 
#include  

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 = 3; 

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

你可能感兴趣的:(c/c++代码)