Consider the following C code snippet that checks if the 3rd bit (bit index 2) of a number is set. What will be printed?
unsigned int num = 10; // binary 1010 if (num & (1 << 2)) { printf("Bit is set\n"); } else { printf("Bit is not set\n"); }
Remember that bits are counted from 0 starting at the least significant bit.
The number 10 in binary is 1010. The bits are indexed 3 2 1 0 from left to right. Bit 2 (third bit) is 0, so the condition is false and "Bit is not set" is printed.
Given the code below, what will be the output?
unsigned char val = 1; // binary 00000001 if (val & 1) { printf("LSB is set\n"); } else { printf("LSB is not set\n"); }
LSB means least significant bit, which is bit 0.
The value 1 in binary is 00000001, so bit 0 is set. The condition is true and "LSB is set" is printed.
What will this code print?
int x = -32; // binary representation depends on two's complement if (x & (1 << 5)) { printf("Bit 5 is set\n"); } else { printf("Bit 5 is not set\n"); }
Remember two's complement representation for negative numbers.
In two's complement, -32 is represented with bit 5 set (since 32 = 1 << 5). So the bitwise AND is non-zero and "Bit 5 is set" is printed.
What error will this code cause?
unsigned int num = 5; if (num & (1U << 32)) { printf("Bit 32 is set\n"); } else { printf("Bit 32 is not set\n"); }
Check the size of unsigned int and the shift operation limits.
Shifting 1 by 32 bits on a 32-bit unsigned int is undefined behavior in C. This can cause unpredictable results or runtime errors.
Given the mask 0xAA55 (hexadecimal), how many bits are set to 1 in its 16-bit binary representation?
Convert hex to binary and count the 1s.
0xAA55 in binary is 1010101001010101. Counting the 1s gives 8 bits set.