Search code examples
gobit-shiftunsigned

Bitshift with unsigned value gives signed result


Doing a bitshift operation with unsigned uint32 variables, why is signed int result received?

func NewNM(log2Dim uint32) {
    SIZE := 1 << (3 * log2Dim) // Why: SIZE type == int
    // ...
}

Solution

  • From the go language reference

    The right operand in a shift expression must have integer type or be an untyped constant representable by a value of type uint. If the left operand of a non-constant shift expression is an untyped constant, it is first implicitly converted to the type it would assume if the shift expression were replaced by its left operand alone.

    and later...

    The shift operators shift the left operand by the shift count specified by the right operand, which must be non-negative. If the shift count is negative at run time, a run-time panic occurs. The shift operators implement arithmetic shifts if the left operand is a signed integer and logical shifts if it is an unsigned integer.

    So the 1 in the expression 1 << (3 * log2Dim) is converted to an int according to the first paragraph, and then the shift is an arithmetic shift according to the second paragraph.