Bits, binary, and bitwise operators
עמוד זה דורש דפדפן עדכני (תומך ב-SharedArrayBuffer). אנא עדכן את Chrome, Edge, Firefox או Safari לגרסה העדכנית ביותר.
English
Numbers are bits
- Inside the computer, every
intis a row of bits — each bit is a0or a1. - We usually read numbers in base 10, but the machine stores them in base 2 (binary).
- Bitwise operators let you look at and change individual bits.
English
Place value and powers of two
- In binary, each position is a power of two: 1, 2, 4, 8, 16, ...
- The byte
00010100is16 + 4 = 20. The rightmost bit is the 1s place. - An 8-bit byte can hold
0to255.

English
Reading a bit with >> and & 1
- The shift
n >> imoves the bits right byiplaces, so bitilands in the 1s place. - The mask
& 1keeps only that lowest bit, giving0or1. - So
(n >> i) & 1reads the value of bit numberi.
English
The bitwise operators
&(and),|(or),^(xor),~(not) combine numbers bit by bit.<<and>>shift bits left or right. For a non-negative value whose doubled result is representable, shifting left by 1 doubles it.- These are the tools for masks, flags, and low-level tricks.

English
#include <stdio.h>
int main(void) {
int n = 20;
for (int i = 7; i >= 0; i--) { // from the highest bit down
printf("%d", (n >> i) & 1);
}
printf("\n"); // 00010100
return 0;
}
English
Common mistakes
&is bitwise AND and&&is logical AND — do not confuse them.- For non-negative values where the result is representable,
<< 1doubles the value and>> 1divides it by 2, rounding down.
English
Now you try
- Use
(n >> i) & 1to read biti, and a loop to look at every bit. - For
count_bitsandget_bit, the parameter isunsigned int. Do not write amainfor those.
חקור
Bitwise operators
& | ^ ~ << >> work on each ביט of a byte independently.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
Complete int count_bits(unsigned int n) so it returns how many bits of n are 1. Use & 1 וגם >> in a loop. Do לא write a main.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
Complete int get_bit(unsigned int n, int i) so it returns bit number i of n (0 או 1). Use (n >> i) & 1. Do לא write a main.
לחץ על הרץ כדי לראות את התוצא כאן.
רמת קושי 3/5 · 200 מטבעות + בונוס קטן בהשלמה הראשונה היום
The byte n is given. In main, print its 8-bit binary form (most significant bit first), then a newline. For 20 that is 00010100.
לחץ על הרץ כדי לראות את התוצא כאן.