Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

bit manipulation — concept C23

Bit operations act on integer representations, and unsigned types are the safest choice for masks. `CHAR_BIT` gives the number of bits in a byte; a negative shift count or one not smaller than the promoted left operand width is undefined, and shifting a negative signed value also needs special care.

Version: C23

Syntax

bit manipulation

Bit operations act on integer representations, and unsigned types are the safest choice for masks. CHAR_BIT gives the number of bits in a byte; a negative shift count or one not smaller than the promoted left operand width is undefined, and shifting a negative signed value also needs special care.

Bit masks are useful for permission flags, device registers, and protocol fields. Give each flag an unsigned value, combine it with |, test it with &, and extract a field by shifting first and then applying a mask of known width.

Check shifts by zero and by the type width, promotion of small integer types before the operation, and conversion of a mask to the intended type. When data leaves the process, define byte order; a numeric value and its byte representation are different contracts.

Examples

#include <stdio.h>

int main(void) {
    unsigned permissions = 0x5u;
    printf("%u\n", (permissions >> 2) & 1u);
    return 0;
}

Result

1

Bit operations act on integer representations, and unsigned types are the safest choice for masks. `CHAR_BIT` gives the number of bits in a byte; a negative shift count or one not smaller than the promoted left operand width is undefined, and shifting a negative signed value also needs special care.

Sources