Golang:如何获得首次字节
我有一个哈希:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以检查位和操作员的结果
you could just check the result of bitwise and operator
哈希的
sum()
函数返回一个字节。您想隔离第一个字节的第一位,对吗?这是一个简单的问题。 2或3个机器说明最多。
根据您的“第一位”的含义,
这为您提供了一个字节的高序/最重要/最左的位:
这为您提供了一个字节的低序/最不重要/最右边的位:
请注意,上述适用于任何整数类型:唯一的区别是
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:
And this gives you the low-order/least significant/rightmost bit of a byte:
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).