比较两个数组中的位

时间:2016-01-23 17:41:24

标签: go

我坚持使用ex4.1这本书说:
编写一个函数,计算两个SHA256哈希中不同的位数。

我提出的部分解决方案粘贴在下面,但它是错误的 - 它计算不同字节的数量而不是位数。 你能指点我正确的方向吗?

package main

import (
    "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 个答案:

答案 0 :(得分:2)

  

The Go Programming Language

     

Alan A. A. Donovan·Brian W.Kernighan

     

练习4.1:编写一个计算位数的函数   两个SHA256哈希值不同。

  

The C Programming Language

     

Brian W.Kernighan·Dennis M. Ritchie

     

练习2-9。在二进制补码系统中,x &= (x-1)删除   x中最右边的1位。用这个观察写得更快   版本bitcount

  

Bit Twiddling Hacks

     Sean Eron Anderson

     

Counting bits set, Brian Kernighan's way

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

答案 1 :(得分:1)

我将如何做到这一点

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
}

Playground