linehk / gopl

gopl(The Go Programming Language) is a project that contains all the sample code and all exercise answers in the Go Programming Language.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

exercise4.1 中的与比较问题

wei98k opened this issue · comments

这儿为什么是要与后比较, 而不能是直接 b1 != b2

if b1&mask != b2&mask {

原代码的意图是比较单个bit 位不同的个数
b1&mask 这是在清除其他bit位

比如 b1 = 01101101 b2 = 01100100

当mask = 00000001时
b1 & mask -> 00000001
b2 & mask -> 00000000
所以b1 和 b2 最后1个bit位是不相同的

当mask = 00000010时
b1 & mask -> 00000000
b2 & mask -> 00000000
所以b1和b2倒数第二个bit位是相同的

如果不进行 b1&mask != b2&mask 直接进行 b1 != b2
那么结果永远是true