douhao6557 2016-01-23 17:41
浏览 65
已采纳

比较两个数组中的位

I've got stuck with ex4.1 for the book which says:
Write a function that counts the number of bits that are different in two SHA256 hashes.

The partial solution I came up with is pasted below, but it's wrong - it counts number of different bytes not bits. Could you please point me in the right direction?

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
", s1, h1, h1) 
    fmt.Printf("s2: %s h2: %X h2 type: %T
", s2, h2, h2) 
    fmt.Printf("Number of different bits: %d
", 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条回答 默认 最新

  • ds3422222222 2016-01-23 18:40
    关注

    The Go Programming Language

    Alan A. A. Donovan · Brian W.Kernighan

    Exercise 4.1: Write a function that counts the number of bits that are different in two SHA256 hashes.


    The C Programming Language

    Brian W.Kernighan · Dennis M. Ritchie

    Exercise 2-9. In a two's complement number system, x &= (x-1) deletes the rightmost 1-bit in x. Use this observation to write a faster version of 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
    }
    

    For exercise 4.1, you are counting the number of bytes that are different. Count the number of bits that are different. For example,

    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))
    }
    

    Output:

    139
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100