Bits, binary, and bitwise operators · 位、二进制与按位运算
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.
数字就是一串位
- 在计算机内部,每个
int都是一排位 —— 每个位是0或1。 - 我们通常用十进制读数字,但机器把它们存成二进制(基数 2)。
- 按位运算符让你查看和改动单个的位。
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.
位值与 2 的幂
- 在二进制里,每个位置都是一个 2 的幂:1、2、4、8、16……
- 字节
00010100是16 + 4 = 20。最右边的位是个位(1 的位)。 - 一个 8 位的字节能存
0到255。
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.
用 >> 和 & 1 读取一个位
- 移位
n >> i把所有位向右移i位,这样第i位就落到个位上。 - 掩码
& 1只保留最低那一位,得到0或1。 - 所以
(n >> i) & 1读取第i位的值。
The bitwise operators
&(and),|(or),^(xor),~(not) combine numbers bit by bit.<<and>>shift bits left or right. Shifting left by 1 doubles a number.- These are the tools for masks, flags, and low-level tricks.
按位运算符
&(与)、|(或)、^(异或)、~(非)把数字一位一位地组合起来。<<和>>把位向左或向右移动。向左移 1 位会让数字翻倍。- 这些是做掩码、标志位和底层技巧的工具。
#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;
}
Common mistakes
&is bitwise AND and&&is logical AND — do not confuse them.<< 1doubles a value;>> 1halves it.
常见错误
&是按位与,&&是逻辑与——别混淆。<< 1让值翻倍;>> 1让值减半。
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.
现在轮到你了
- 用
(n >> i) & 1读取第i位,用循环查看每一位。 count_bits和get_bit的参数是unsigned int。这两个不要写main。
Bitwise operators · 位运算符
& | ^ ~ << >> work on each bit of a byte independently. · & | ^ ~ << >> 对一个字节的每一位独立运算。
Complete int count_bits(unsigned int n) so it returns how many bits of n are 1. Use & 1 and >> in a loop. Do not · 不 write a main. · 完成 int count_bits(unsigned int n),让它返回 n 里有多少个位是 1。在循环里用 & 1 和 >>。不要写 main。
Click Run to see the output here. · 点击“运行”查看此处输出。
Complete int get_bit(unsigned int n, int i) so it returns bit number i of n (0 or · 或 1). Use (n >> i) & 1. Do not · 不 write a main. · 完成 int get_bit(unsigned int n, int i),让它返回 n 的第 i 位(0 或 1)。用 (n >> i) & 1。不要写 main。
Click Run to see the output here. · 点击“运行”查看此处输出。
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. · 字节 n 已给出。在 main 里面,打印它的 8 位二进制形式(从最高位开始),然后换行。对于 20,结果是 00010100。
Click Run to see the output here. · 点击“运行”查看此处输出。