Bits and binary · 比特与二进制
Bits: the smallest piece of data
- A bit is one digit that is either
0or1. - Computers store everything — numbers, text, images — as bits.
- One bit alone is small, so we group many bits together.
比特:最小的数据单位
- 比特(bit)是一个数字,要么是
0,要么是1。 - 计算机把所有东西 —— 数字、文字、图像 —— 都存成比特。
- 单个比特很小,所以我们把很多比特组合在一起。
Why computers use binary
- A computer chip has tiny switches. Each switch is on or off.
on=1andoff=0. So two states fit a chip perfectly.- Counting with only
0and1is called binary (base 2).
为什么计算机用二进制
- 计算机芯片里有许多小开关。每个开关要么开,要么关。
- 开 =
1,关 =0。所以两种状态正好适合芯片。 - 只用
0和1来计数叫作二进制(binary,二进制)。
How binary counts
- Our normal numbers use base 10 (digits
0–9). - Binary uses base 2. Each place is worth twice the place on its right.
- The places are
8 4 2 1. So1101means8 + 4 + 0 + 1 = 13.
二进制如何计数
- 我们平常的数字用十进制(数字
0–9)。 - 二进制用基数 2。每一位的大小是它右边那一位的两倍。
- 这些位是
8 4 2 1。所以1101表示8 + 4 + 0 + 1 = 13。
place: 8 4 2 1
bits: 1 1 0 1 -> 8 + 4 + 0 + 1 = 13
Python can convert for you
bin(13)gives the string'0b1101'. The0bjust means "this is binary".int("1101", 2)reads"1101"as base 2 and gives13.- These two functions go in opposite directions.
Python 可以帮你转换
bin(13)给出字符串'0b1101'。0b只是表示"这是二进制"。int("1101", 2)把"1101"当作基数 2 来读,得到13。- 这两个函数的方向正好相反。
print(bin(13)) # decimal -> binary
print(int("1101", 2)) # binary -> decimal
Fixed bits and overflow
- A computer keeps a number in a fixed number of bits.
- With 4 bits you can store
0to15— that is2**4 = 16different values. - If a result is too big, it wraps around back to
0. This is overflow.
固定位数与溢出
- 计算机用固定的位数来保存一个数字。
- 用 4 个比特可以存
0到15—— 也就是2**4 = 16个不同的值。 - 如果结果太大,它会绕回到
0。这叫作溢出(overflow)。
print(2 ** 4) # how many values 4 bits hold = 16
print((15 + 3) % 16) # 18 is too big, so it wraps to 2
Common mistakes
nbits store2**ndifferent values, from0to2**n - 1.- Binary is base 2: each place is worth twice the one to its right.
常见错误
n个比特能存2**n种不同的值,从0到2**n - 1。- 二进制是二进制(基数 2):每一位是右边那位的两倍。
Now you try
- Type your code below and press Run to see the output.
- Press Check answer to test it.
现在轮到你
- 在下面输入你的代码,按运行查看输出。
- 按检查答案来测试它。
Binary counts in powers of 2 · 二进制按 2 的幂计数
Each bit is a power of two; lit bits add up to the value. · 每一位都是 2 的幂;为 1 的位加起来就是这个值。
Use bin(...) to print the binary form of 20. The output should look like 0b10100. · 用 bin(...) 打印 20 的二进制形式。输出应该是 0b10100 这样的样子。
Click Run to see the output here. · 点击“运行”查看此处输出。
The binary string "110" is a number. Use int(s, 2) to print it as a normal (decimal) number. · 二进制字符串 "110" 是一个数字。用 int(s, 2) 把它打印成普通的(十进制)数字。
Click Run to see the output here. · 点击“运行”查看此处输出。
A counter has 5 bits, so it holds 2**5 = 32 values. Store 2**5 in · 入 size. Then store (30 + 5) % size in · 入 result to show how the value wraps around (overflow). · 一个计数器有 5 个比特,所以它能存 2**5 = 32 个值。把 2**5 存进 size。然后把 (30 + 5) % size 存进 result,展示数值如何绕回(溢出)。
Click Run to see the output here. · 点击“运行”查看此处输出。