Bits and binary
C Programming Lesson 21 2:30 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Inside the machine an int is not a decimal number; it is a row of bits, each one a nought or a one.
在机器内部,一个 int 不是十进制数; 它是一排二进制位,每一位不是 0 就是 1。
Reading it works exactly like ordinary place value, except the places are powers of two: one, two, four, eight, doubling as you go left.
读它的方法和平常的位值完全一样,只不过每一位是 2 的幂: 1、2、4、8,越往左每次翻一倍。
Take this byte.
看这个字节。
Two of its bits are set — the sixteens and the fours — so its value is sixteen plus four, which is twenty.
有两位是 1——16 那一位和 4 那一位—— 所以它的值是 16 加 4,也就是 20。
Eight bits reach from nought to two hundred and fifty-five.
八个二进制位能表示 0 到 255。
Suppose you want one particular bit — say bit two.
假设你想要其中某一位——比如第 2 位。
Two moves get it.
两步就能拿到。
First shift the whole number right by two, and the bit you wanted lands in the ones place.
先把整个数右移 2 位,你要的那一位就落到了个位上。
Then and it with one, which keeps the ones place and wipes out everything else, leaving a nought or a one.
然后和 1 做按位与,这会保留个位、抹掉其它所有位, 留下的不是 0 就是 1。
That is the second task, and the answer is one line long.
这就是第二道题,答案只有一行。
There are four you should know.
有四个你应该掌握。
And gives a one only where both bits are one.
按位与,只有两个位都是 1 时才给出 1。
Or gives a one where either one is set.
按位或,只要有一个是 1 就给出 1。
Exclusive-or gives a one only where they differ.
异或,只有两个位不同时才给出 1。
And shifting left by one doubles the number, exactly as adding a nought on the right multiplies by ten in decimal.
而左移一位会让这个数翻倍, 就像十进制里在右边补一个 0 就是乘以 10 一样。
Now the warning: single ampersand works bit by bit, double ampersand is the logical and from lesson three.
现在是警告:单个 & 是逐位运算, 两个 && 是第 3 课里的逻辑与。
One character, completely different job.
差一个字符,做的完全是两回事。
The third task prints a byte in binary, and there is one thing to get right: the direction.
第三道题把一个字节按二进制打印出来, 只有一件事要弄对:方向。
We write the highest bit on the left, but a loop from nought upwards reads the lowest bit first, which would print it backwards.
我们把最高位写在左边, 但一个从 0 往上数的循环,先读到的是最低位,那会把它打印反。
So start at seven and count down to nought, reading each bit with shift-and-mask as you go.
所以要从 7 开始往下数到 0, 一路用“移位再取与”读出每一位。
Twenty comes out as nought nought nought one nought one nought nought.
20 打印出来就是 00010100。
Four things to take with you.
带走四点。
One: a number is a row of bits, and each place is a power of two.
第一:一个数就是一排二进制位,每一位是 2 的一个幂。
Two: n shifted right by i puts bit i in the ones place.
第二:把 n 右移 i 位,第 i 位就到了个位上。
Three: and-one keeps that bit and clears the rest.
第三:和 1 做按位与,保留那一位、清掉其余的。
Four: single ampersand is bitwise, double is logical — do not swap them.
第四:单个 & 是按位运算,两个 && 是逻辑运算——别弄混。
Now do the three tasks; the first one counts how many bits are set.
现在去做那三道题;第一题是数有多少位是 1。