0
0
Embedded Cprogramming~5 mins

AND for masking bits in Embedded C

Choose your learning style9 modes available
Introduction
AND is used to keep certain bits of a number while turning others off. This helps us focus on specific parts of data.
You want to check if a specific light is on in a group of lights.
You need to get only the last 4 bits of a number to read a small value.
You want to clear some bits but keep others unchanged.
You want to test if a particular feature flag is active in a settings byte.
Syntax
Embedded C
result = value & mask;
The '&' symbol means AND in C language.
The mask is a number where bits you want to keep are 1, and bits to ignore are 0.
Examples
This keeps bits where mask has 1s and turns off others.
Embedded C
int value = 0b1101;  // binary 1101 (decimal 13)
int mask = 0b0101;   // binary 0101 (decimal 5)
int result = value & mask;  // result is 0b0101 (decimal 5)
This extracts the last 4 bits of value.
Embedded C
int value = 0xFF;    // hex FF (decimal 255)
int mask = 0x0F;     // hex 0F (decimal 15)
int result = value & mask;  // result is 0x0F (decimal 15)
Sample Program
This program uses AND to keep only the last 4 bits of a byte and prints the result in binary and decimal.
Embedded C
#include <stdio.h>

int main() {
    unsigned char value = 0b10101100;  // example byte
    unsigned char mask = 0b00001111;   // mask to keep last 4 bits
    unsigned char result = value & mask;

    printf("Value in binary: 0b10101100\n");
    printf("Mask in binary:  0b00001111\n");
    printf("Result in binary: 0b");

    for (int i = 7; i >= 0; i--) {
        printf("%d", (result >> i) & 1);
    }
    printf("\n");

    printf("Result in decimal: %d\n", result);
    return 0;
}
OutputSuccess
Important Notes
Mask bits set to 1 keep the original bit value; bits set to 0 turn off that bit.
AND masking does not change the original value; it creates a new result.
Use binary or hex notation to clearly see which bits are set in the mask.
Summary
AND with a mask keeps only the bits you want and turns off others.
Use 1s in the mask where you want to keep bits, 0s where you want to ignore.
This is useful to extract or check parts of data stored in bits.