Introduction
AND is used to keep certain bits of a number while turning others off. This helps us focus on specific parts of data.
result = value & mask;
int value = 0b1101; // binary 1101 (decimal 13) int mask = 0b0101; // binary 0101 (decimal 5) int result = value & mask; // result is 0b0101 (decimal 5)
int value = 0xFF; // hex FF (decimal 255) int mask = 0x0F; // hex 0F (decimal 15) int result = value & mask; // result is 0x0F (decimal 15)
#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; }
val in embedded C?unsigned char val = 0xAB; // 10101011 in binary
unsigned char mask = 0x0F; // 00001111 in binary
unsigned char result = val & mask;
printf("%02X", result);val, but it does not work as expected. What is the error?unsigned char val = 0xAB; // 10101011
unsigned char mask = 0xF0; // 11110000
unsigned char result = val | mask;
printf("%X", result);uint16_t data. The upper 8 bits represent temperature, and the lower 8 bits represent humidity. How do you extract only the temperature value using AND masking?Pass the test and this pattern moves unknown