duanchou6534
2018-11-06 07:12 阅读 381
已采纳

Golang中的0x1是什么意思?

I'm trying to understand this piece of code for returning how many zeroes a byte array is prefixed with but I'm not sure what 0x1 is. Google search isn't helpful, but I'm assuming 0x1 is returning the first bit? What are these called?

Also, I know this is a separate question but I don't think it warrants a new thread: I don't quite understand why we're nesting a loop here, bit shifting, and subtracting j from 7. Is this how the byte is transformed into binary?

IdLength := 32
func PrefixLen(count [IdLength]byte) int {
    for i := 0; i < IdLength; i++ {
        for j := 0; j < 8; j++ {
            if (count[i]>>uint8(7-j))&0x1 != 0 {
                return i*8 + j
            }
        }
    }
    return IdLength*8 - 1
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanmei1922 duanmei1922 2018-11-06 07:29

    0x1 is just the hexadecimal notation of number 1. You & some integer with 0x1 to get its least significant (rightmost) bit. You write 0x1 instead of 1 when using a bit mask because it's easier to convert from base 16 than from base 10 to base 2.

    For the second question, what func PrefixLen does is finding the number of consecutive zeroes on the beginning of count. The outer loop does one byte each time, and the inner loop deals with separate bits: when j=0 it shifts 7 to the right thus getting the first bit from left, when j=1 it shifts 6 getting the second bit, and so on. When a bit of 1 is encountered it returns the count of bits already checked.

    点赞 评论 复制链接分享

相关推荐