📜  C中的CHAR_BIT(1)

📅  最后修改于: 2023-12-03 15:30:14.437000             🧑  作者: Mango

C中的CHAR_BIT介绍

在C语言中,CHAR_BIT是一个宏定义,表示一个字节(byte)中的bit数。

#include <limits.h>
#define CHAR_BIT 8
使用示例
#include <stdio.h>
#include <limits.h>

int main() {
    printf("A byte has %d bits.\n", CHAR_BIT);
    printf("The maximum value of a char is %d.\n", CHAR_MAX);
    printf("The minimum value of a char is %d.\n", CHAR_MIN);
    printf("The maximum value of an unsigned char is %u.\n", UCHAR_MAX);
    printf("The maximum value of a short is %d.\n", SHRT_MAX);
    printf("The minimum value of a short is %d.\n", SHRT_MIN);
    printf("The maximum value of an unsigned short is %u.\n", USHRT_MAX);
    printf("The maximum value of an int is %d.\n", INT_MAX);
    printf("The minimum value of an int is %d.\n", INT_MIN);
    printf("The maximum value of an unsigned int is %u.\n", UINT_MAX);
    printf("The maximum value of a long is %ld.\n", LONG_MAX);
    printf("The minimum value of a long is %ld.\n", LONG_MIN);
    printf("The maximum value of an unsigned long is %lu.\n", ULONG_MAX);
    printf("The maximum value of a long long is %lld.\n", LLONG_MAX);
    printf("The minimum value of a long long is %lld.\n", LLONG_MIN);
    printf("The maximum value of an unsigned long long is %llu.\n", ULLONG_MAX);
}

以上代码可以输出各种数据类型的最大值和最小值。

案例:使用CHAR_BIT进行位操作
#include <stdio.h>
#include <limits.h>

int main() {
    unsigned char a = 0xAA;
    unsigned char mask = 1 << (CHAR_BIT - 1);
    for (int i = 0; i < CHAR_BIT; i++) {
        printf("Bit %d of %x is %d\n", i, a, ((a & mask) > 0));
        mask >>= 1;
    }
}

以上代码可以输出一个字节的每一位的值,其思路是通过右移mask的方式逐位检查。