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 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥20 和学习数据的传参方式,选择正确的传参方式有关
  • ¥15 这是网络安全里面的poem code
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路