Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

CHAR_BIT trong C++


CHAR_BIT là số bit trong một char. Khai báo trong header <limits.h> (hoặc <climits>). Thường là 8 bit/byte.

Ví dụ

#include <bits/stdc++.h>
using namespace std;

int main() {
    int x = 28;
    int a = CHAR_BIT * sizeof(x);
    stack<bool> s;
    cout << "The number is: " << x << endl;
    for (int i = 1; i <= a; i++) {
        s.push(x % 2);
        x = x / 2;
    }
    cout << "The number of bits in a byte: " << CHAR_BIT << endl;
    for (int i = 1; i <= a; i++) {
        cout << s.top();
        s.pop();
        if (i % CHAR_BIT == 0)
            cout << " ";
    }
    return 0;
}

Kết quả

The number is: 28
The number of bits in a byte: 8
00000000 00000000 00000000 00011100

Chương trình in nhị phân của số 28 (4 byte = 32 bit), dùng CHAR_BIT = 8 để ngắt dòng mỗi byte.