如何从golang中的字节中获取位?

alm*_*mel 3 go

我正在尝试计算两个字节之间的汉明距离,这样

HammingDist(byte(255), byte(0)) == 8

我需要每个字节中的位,但是我无法在任何内置包中找到任何功能.那么,byte(1)我如何获得位表示00000001?

ksk*_*cou 13

你可以fmt.Sprintf(%08b, ..)像其他人已经建议的那样看到比特的可视化表示.

但是,如果要在操作中使用这些位,例如计算汉明距离,则需要使用按位运算符.

要计算一个字节的第n位,您需要bitwise AND将该字节与另一个字节进行比较,该字节的第n位设置为1,其余字节设置为0(也称为屏蔽).换句话说,该另一个字节(掩码)是数字2 ^ n-1.

例如,要查找数字13(00001101)的第1位,我们必须使用2 ^ 0 = 1(00000001)对其进行掩码.我们将两个数字上执行按位AND的输出与掩码进行比较.如果它们相等,则意味着第n位为1,否则为0.我们继续这样并找到所有位.Go代码中的插图:

fmt.Print(13 & 1) // Output: 1 -> 1
fmt.Print(13 & 2) // Output: 0 -> 0
fmt.Print(13 & 4) // Output: 4 -> 1
fmt.Print(13 & 8) // Output: 8 -> 1
// Not necessary to continue, but shown for the sake of the example
fmt.Print(13 & 16) // Output: 0 -> 0
fmt.Print(13 & 32) // Output: 0 -> 0
fmt.Print(13 & 64) // Output: 0 -> 0
fmt.Print(13 & 128) // Output: 0 -> 0
Run Code Online (Sandbox Code Playgroud)

因此,二进制13是00001101

这是我最近写的一个函数,用于计算两个字节数组之间的汉明距离.在您的情况下,只传递一个由单个字节组成的数组

func hamming(a, b []byte) (int, error) {
    if len(a) != len(b) {
        return 0, errors.New("a b are not the same length")
    }

    diff := 0
    for i := 0; i < len(a); i++ {
        b1 := a[i]
        b2 := b[i]
        for j := 0; j < 8; j++ {
            mask := byte(1 << uint(j))
            if (b1 & mask) != (b2 & mask) {
                diff++
            }
        }
    }
    return diff, nil
}
Run Code Online (Sandbox Code Playgroud)

去游乐场:https://play.golang.org/p/O1EGdzDYAn

  • 出于好奇,你知道为什么“%b”单独只显示 6 位吗? (2认同)

lof*_*cek 7

fmt.Sprintf("%08b", byte(1)) 是个好主意。它向您展示了数字是如何在内部存储的。计算汉明距离(非常无聊)的示例可能是:

package main

import (
    "fmt"
)

func HamDist(n1,n2 uint8) uint8 {
    var w uint8 = 0
    if n1&1 != n2&1 {
        w++
    }
    if n1&2 != n2&2 {
        w++
    }
    if n1&4 != n2&4 {
        w++
    }
    if n1&8 != n2&8 {
        w++
    }
    if n1&16 != n2&16 {
        w++
    }
    if n1&32 != n2&32 {
        w++
    }
    if n1&64 != n2&64 {
        w++
    }
    if n1&128 != n2&128 {
        w++
    }
    return w
}

func main() {
    fmt.Println(HamDist(255,0))
}
Run Code Online (Sandbox Code Playgroud)

现在为您完成任务:

  1. 使用循环重写代码
  2. 扩展程序以计算 16 位数字的汉明距离
  3. 如果您已经定义了一个计算汉明权重的函数,请考虑异或运算符的作用以及是否应该更容易计算汉明距离。


che*_*ong 5

import "math/bits"

bits.OnesCount8(byte(0) ^ byte(255))
Run Code Online (Sandbox Code Playgroud)