duanchou6534 2018-11-06 07:12
浏览 527
已采纳

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 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?