doushi8187 2017-10-23 08:37
浏览 257

Golang有符号数字的左/右移位行为

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
  • 写回答

1条回答 默认 最新

  • doukun1450 2017-10-23 08:47
    关注

    -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.

    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置