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/02/

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 02 main.c Code Diff
UNCHANGED This step does not change this file.
#include <limits.h>
#include <stdio.h>
#include "input.h"
int main(void) {
const int current_year = 2026;
int study_year = 1;
char group = 'A';
int birth_year = read_int("Year of birth: ");
int g1 = read_int("Grade 1: ");
int g2 = read_int("Grade 2: ");
int g3 = read_int("Grade 3: ");
double average = (g1 + g2 + g3) / 3.0;
int age = current_year - birth_year;
printf("Year of study: %d\n", study_year);
printf("Group: PI25%c\n", group);
printf("Age: %d years\n", age);
printf("Average: %.2f\n", average);
printf("In memory: int %zu B, double %zu B, char %zu B\n", sizeof study_year, sizeof average,
sizeof group);
printf("\n");
printf("Largest int: %d\n", INT_MAX);
long long century = 100LL * 365 * 24 * 60 * 60;
printf("100 years: %lld s\n", century);
printf("0.1 + 0.2 = %.17f\n", 0.1 + 0.2);
return 0;
}