time包中的`nsec()`函数

huangapple go评论95阅读模式
英文:

time package `nsec()` function

问题

我对nsec()函数的操作方式感到困惑。它在时间和纳秒掩码的wall属性上应用了AND运算符(该掩码为1<<30-1 => 111111111111111111111111111111),以返回时间对象的纳秒值。我想知道为什么要将一个数字与1&lt;&lt;30-1进行AND运算,因为这样等于原数字本身(因为所有位都是1),所以他们为什么要这样做?

func (t *Time) nsec() int32 {
    return int32(t.wall & nsecMask)
}

主要源代码:
https://cs.opensource.google/go/go/+/refs/tags/go1.16.7:src/time/time.go;l=164;drc=refs%2Ftags%2Fgo1.16.7

英文:

I'm confused about the time package nsec() function operation. It's applying the AND operator on the wall property of the time & nanosecond mask (which is 1<<30-1 => 111111111111111111111111111111) to return the nanosecond value of the time object. I'm wondering that ANDING a number with 1&lt;&lt;30-1 equals the number (because all digits have value 1), so why they're doing it?

func (t *Time) nsec() int32 {
    return int32(t.wall &amp; nsecMask)
}

The main source code:
https://cs.opensource.google/go/go/+/refs/tags/go1.16.7:src/time/time.go;l=164;drc=refs%2Ftags%2Fgo1.16.7

答案1

得分: 2

wall字段的类型是uint64,它包含的不仅仅是纳秒:

// 从高到低的位位置,wall编码了一个1位的标志(hasMonotonic),
// 一个33位的秒字段,和一个30位的墙上时间纳秒字段。

所以他们在这里做的是提取最后的30位来获取纳秒。

英文:

wall field is of type uint64 and it contains more than just
nanoseconds:

// From high to low bit position, wall encodes a 1-bit flag (hasMonotonic),
// a 33-bit seconds field, and a 30-bit wall time nanoseconds field.

So what they're doing here is that they're extracting last 30 bits to
get nanoseconds.

huangapple
  • 本文由 发表于 2021年8月16日 01:18:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/68793782.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定