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

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 05 recursion.c Code Diff
UNCHANGED This step does not change this file.
#include <assert.h>
#include <stdio.h>
/* The digit sum; depth is how many calls deep the function already is.
Before: n >= 0, depth >= 0.
After: the sum of the digits of n. */
int digit_sum(int n, int depth) {
assert(n >= 0 && depth >= 0);
printf("%*sdigit_sum(%d)\n", depth * 2, "", n);
if (n < 10) {
return n;
}
return n % 10 + digit_sum(n / 10, depth + 1);
}
/* n! = 1 * 2 * ... * n.
Before: n is from 0 to 20 (21! doesn't fit in a long long).
After: the factorial of n; 0! = 1. */
long long factorial(int n) {
assert(n >= 0 && n <= 20);
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
int main(void) {
int sum = digit_sum(472, 0);
printf("Digit sum: %d\n", sum);
printf("5! = %lld\n", factorial(5));
printf("20! = %lld\n", factorial(20));
return 0;
}