2 回答

TA貢獻2080條經驗 獲得超4個贊
艾倫·多諾萬·布萊恩·W·克尼漢
練習 4.1:編寫一個函數來計算兩個 SHA256 散列中不同的位數。
布賴恩·W·克尼漢·丹尼斯·M·里奇
練習 2-9。在二進制補碼系統中,
x &= (x-1)
刪除x
. 使用此觀察結果編寫更快的bitcount
.
肖恩·安德森
unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
v &= v - 1; // clear the least significant bit set
}
對于練習 4.1,您正在計算不同的字節數。計算不同的位數。例如,
package main
import (
"crypto/sha256"
"fmt"
)
func BitsDifference(h1, h2 *[sha256.Size]byte) int {
n := 0
for i := range h1 {
for b := h1[i] ^ h2[i]; b != 0; b &= b - 1 {
n++
}
}
return n
}
func main() {
s1 := "unodostresquatro"
s2 := "UNODOSTRESQUATRO"
h1 := sha256.Sum256([]byte(s1))
h2 := sha256.Sum256([]byte(s2))
fmt.Println(BitsDifference(&h1, &h2))
}
輸出:
139

TA貢獻1943條經驗 獲得超7個贊
這是我將如何做到的
package main
import (
"crypto/sha256"
"fmt"
)
var (
s1 string = "unodostresquatro"
s2 string = "UNODOSTRESQUATRO"
h1 = sha256.Sum256([]byte(s1))
h2 = sha256.Sum256([]byte(s2))
)
func main() {
fmt.Printf("s1: %s h1: %X h1 type: %T\n", s1, h1, h1)
fmt.Printf("s2: %s h2: %X h2 type: %T\n", s2, h2, h2)
fmt.Printf("Number of different bits: %d\n", DifferentBits(h1, h2))
}
// bitCount counts the number of bits set in x
func bitCount(x uint8) int {
count := 0
for x != 0 {
x &= x - 1
count++
}
return count
}
func DifferentBits(c1 [32]uint8, c2 [32]uint8) int {
var counter int
for x := range c1 {
counter += bitCount(c1[x] ^ c2[x])
}
return counter
}
- 2 回答
- 0 關注
- 283 瀏覽
添加回答
舉報