Golang:如何获得首次字节

发布于 2025-02-12 07:20:03 字数 261 浏览 1 评论 0原文

我有一个哈希:

b := hash.Sum(nil)

我真的只是对那个字节的第一位感兴趣。是0还是1?

到目前为止,我有这个问题:

s := strconv.FormatInt(int64(b[0]),2)
if s[0] == '0' {
 // it's 0
} else {
  // it's 1
}

但是我确定有一种更优雅(更具性能?)的方式来做到这一点。

I have a hash:

b := hash.Sum(nil)

I am really just interested in the first bit of that byte. Is it 0 or 1?

So far I have this:

s := strconv.FormatInt(int64(b[0]),2)
if s[0] == '0' {
 // it's 0
} else {
  // it's 1
}

But I am sure there is a much more elegant (and more performant?) way to do this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

烟花肆意 2025-02-19 07:20:03

您可以检查位和操作员的结果

if b[0] & 0x1 == 0x1 {
    // it's 1
} else {
    // it's 0
}

you could just check the result of bitwise and operator

if b[0] & 0x1 == 0x1 {
    // it's 1
} else {
    // it's 0
}
〃温暖了心ぐ 2025-02-19 07:20:03

哈希的sum()函数返回一个字节。您想隔离第一个字节的第一位,对吗?

这是一个简单的问题。 2或3个机器说明最多。

根据您的“第一位”的含义,

这为您提供了一个字节的高序/最重要/最左的位:

func HighOrderBit(b byte) byte {
    return (b >> 7) & 0x01
}

这为您提供了一个字节的低序/最不重要/最右边的位:

func LowOrderBit(b byte) byte {
    return (b >> 0) & 0x01
}

请注意,上述适用于任何整数类型:唯一的区别是highorderbit()中正确移动的大小。向右移动的位数是整数类型的大小减去一个(例如,对于64位整数,移位值为64-1或63)。

The Sum() function of a hash returns a slice of bytes. You want to isolate the first bit of the first byte, correct?

It's a simple matter of bit-twiddling. 2 or 3 machine instructions at most.

Depending on what you mean by "first bit",

This gives you the high-order/most significant/leftmost bit of a byte:

func HighOrderBit(b byte) byte {
    return (b >> 7) & 0x01
}

And this gives you the low-order/least significant/rightmost bit of a byte:

func LowOrderBit(b byte) byte {
    return (b >> 0) & 0x01
}

Note that the above works for any integer type: the only difference being the size of the right shift in highOrderBit(). The number of bits to shift right is the size of the integer type in bits minus one (e.g., for a 64-bit integer, the shift value is 64-1, or 63).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文