time package `nsec()` function

Viewed 49

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<<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 & 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 Answers

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.

Related