Skip to the task
Layout
Back to classic view

You are looking ahead. Your place is still task 1: Memory.

READTask 2 of 25 · step 2: Bits and bit operationsBits and bit operations
Bits and bit operations in practice/01/

Binary notation, unsigned, the operators & | ^ ~ << >> and masks to set, clear and test one bit.

Details & hint

A byte is 8 bits, each bit 0 or 1. Bit operations change and test single bits: that's how permissions, settings and colours are stored.

Binary and hexadecimal

12 in binary is 00001100 = 8 + 4. Each position is a power of two: 128, 64, 32, 16, 8, 4, 2, 1.

Long binary strings are hard to read, so the hexadecimal system is used: one digit 0–F is exactly 4 bits.

decimal binary hexadecimal
12 0000 1100 0x0C
255 1111 1111 0xFF
31 0001 1111 0x1F

In C code a hexadecimal number is written with 0x and printed with %X: printf("%X", 255u) prints FF.

unsigned

Use unsigned int for bit operations: it has no negative values, and all 32 bits are simply the number. With int, a shift into the sign bit is undefined behaviour: CI with UBSan stops 1 << 31 with left shift of 1 by 31 places cannot be represented in type 'int'. Write 1u << 31: the u makes the constant unsigned.

Operations

operation what it does 12u and 10u
a & b 1 where both are 1 00001000 = 8
a | b 1 where at least one is 1 00001110 = 14
a ^ b 1 where exactly one is 1 00000110 = 6
~a flips every bit 11110011 (lowest 8)
a << 1 shifts left: × 2 00011000 = 24
a >> 2 shifts right: / 4 00000011 = 3

& and && are different things: & works on each bit, && on the whole condition (true or false). The same goes for | and ||.

Masks

A mask is a number with only the bits of interest switched on. For example permissions (perms): READ = 1u (001), WRITE = 2u (010), EXECUTE = 4u (100).

to how
switch a bit on perms |= WRITE;
switch a bit off perms &= ~WRITE;
test a bit if (perms & WRITE)
toggle a bit perms ^= WRITE;

One more common move is pulling out a byte: (x >> 8) & 0xFFu shifts the second byte to the start and keeps only its 8 bits. In the homework you'll split a colour this way.

practice 01 main.c Code Diff
UNCHANGED This step does not change this file.
#include <stdio.h>
int main(void) {
printf("Hello, world!\n");
printf("\n");
printf("Algorithm: the average of grades\n");
printf("1. Add up all the grades.\n");
printf("2. Count how many grades there are.\n");
printf("3. Divide the sum by the count.\n");
printf("4. Print the answer.\n");
printf("\n");
printf("Grade\tMeaning\n");
printf("10\t\"excellent\"\n");
printf("5\t\"satisfactory\"\n");
printf("File: C:\\course\\practice\\01\\main.c\n");
printf("Done: 100%%\n");
return 0;
}