← The C Language Lesson 66 of 77 · 10 XP

Bitwise operations

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

An integer is a set of bits. Bitwise operators work with each bit separately:

example (5 = 0101, 3 = 0011)
& AND 5 & 3 = 0001 = 1
\| OR 5 \| 3 = 0111 = 7
^ exclusive OR (XOR) 5 ^ 3 = 0110 = 6
~ NOT inverts all the bits
<< shift left 1 << 3 = 1000 = 8 (multiplying by 2³)
>> shift right 8 >> 2 = 2 (dividing by 2²)

The main use is flags: many yes/no values in one number.

#define FLAG_READ  (1u << 0)    // 001
#define FLAG_WRITE (1u << 1)    // 010
#define FLAG_EXEC  (1u << 2)    // 100

unsigned perms = FLAG_READ | FLAG_WRITE;   // set
if (perms & FLAG_WRITE) { ... }            // check
perms &= ~FLAG_WRITE;                      // clear
perms ^= FLAG_EXEC;                        // toggle

File permissions in Linux (chmod 755) work exactly like this. Another trick: n & 1 checks whether a number is odd, and n & (n - 1) clears the lowest set bit.

Shift unsigned numbers: shifting negative numbers, and shifting by the width of the type or more, is undefined behaviour.

Task. Read a non-negative number and print, separated by a space: the number of set bits in it and the number itself in binary (without leading zeros; for 0 — 0).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.