亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

比較兩個數組中的位

比較兩個數組中的位

Go
陪伴而非守候 2021-12-07 15:13:58
我一直堅持使用 ex4.1 這本書說:編寫一個函數來計算兩個 SHA256 哈希中不同的位數。我想出的部分解決方案粘貼在下面,但它是錯誤的 - 它計算不同字節的數量而不是位。你能指出我正確的方向嗎?package mainimport (    "crypto/sha256"    "fmt")var s1 string = "unodostresquatro"var s2 string = "UNODOSTRESQUATRO"var h1 = sha256.Sum256([]byte(s1))var 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", 8 * DifferentBits(h1, h2))}func DifferentBits(c1 [32]uint8, c2 [32]uint8) int {    var counter int     for x := range c1 {        if c1[x] != c2[x] {            counter += 1        }    }       return counter}
查看完整描述

2 回答

?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

Go 編程語言

艾倫·多諾萬·布萊恩·W·克尼漢

練習 4.1:編寫一個函數來計算兩個 SHA256 散列中不同的位數。


C 編程語言

布賴恩·W·克尼漢·丹尼斯·M·里奇

練習 2-9。在二進制補碼系統中,x &= (x-1)刪除x. 使用此觀察結果編寫更快的bitcount.


Bit Twiddling Hacks

肖恩·安德森

計數位設置,Brian Kernighan 的方式

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


查看完整回答
反對 回復 2021-12-07
?
楊__羊羊

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

}



查看完整回答
反對 回復 2021-12-07
  • 2 回答
  • 0 關注
  • 283 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號