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

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 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思