Can someone please explain the left/right shift behaviour in Golang. Please refer the sample code here: https://play.golang.org/p/7vjwCbOEkw
package main
import (
"fmt"
)
func main() {
var lf int8 = -3
fmt.Printf("-3 : %08b
", lf)
fmt.Printf("<<1: %08b
", lf<<1)
fmt.Printf("<<2: %08b
", lf<<2)
fmt.Printf("<<3: %08b
", lf<<3)
fmt.Printf("<<4: %08b
", lf<<4)
fmt.Printf("<<5: %08b, %d
", lf<<5, lf<<5)
fmt.Printf("<<6: %08b, %d
", lf<<6, lf<<6)
fmt.Printf("<<7: %08b, %d
", lf<<7, lf<<7)
fmt.Printf("<<8: %08b, %d
", lf<<8, lf<<8)
fmt.Printf("<<9: %08b, %d
", lf<<9, lf<<9)
}
-3 : -0000011
<<1: -0000110
<<2: -0001100
<<3: -0011000
<<4: -0110000
<<5: -1100000, -96
<<6: 01000000, 64
<<7: -10000000, -128
<<8: 00000000, 0
<<9: 00000000, 0
-3
is, in two's complement, 11111101
and what you see when the program prints -0000011
is a -
and the binary representation of the absolute value of the number. In two's complement, the highest bit is 0
for positive (including zero), and 1
for negative numbers. If you shift this number (11111101
) left, the lower 7 bits move one to the left and a 0
comes in from the right, replacing the lowest bit. Shifting as you do in your example will result in:
11111101 -3 11111010 -6 11110100 -12 11101000 -24 11010000 -48 10100000 -96 01000000 64 10000000 -128 00000000 0 00000000 0 ...
You just have to consider all the bit patterns as two's complement, once you know how that works, everything will make sense.