【问题标题】:Go - Perform unsigned shift operationGo - 执行无符号移位操作
【发布时间】:2016-01-24 23:55:21
【问题描述】:

在 Go 中是否有执行无符号移位(即无符号右移)操作? Java中类似的东西

0xFF >>> 3

在这件事上我唯一能找到的就是这个post,但我不确定我必须做什么。

提前致谢。

【问题讨论】:

    标签: go binary-operators


    【解决方案1】:

    The Go Programming Language Specification

    Numeric types

    数字类型表示整数或浮点值的集合。 预先声明的独立于架构的数字类型包括:

    uint8       the set of all unsigned  8-bit integers (0 to 255)
    uint16      the set of all unsigned 16-bit integers (0 to 65535)
    uint32      the set of all unsigned 32-bit integers (0 to 4294967295)
    uint64      the set of all unsigned 64-bit integers (0 to 18446744073709551615)
    
    int8        the set of all signed  8-bit integers (-128 to 127)
    int16       the set of all signed 16-bit integers (-32768 to 32767)
    int32       the set of all signed 32-bit integers (-2147483648 to 2147483647)
    int64       the set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)
    
    byte        alias for uint8
    rune        alias for int32
    

    n 位整数的值是 n 位宽,用 二进制补码算法。

    还有一组预先声明的数字类型 实现特定的大小:

    uint     either 32 or 64 bits
    int      same size as uint
    uintptr  an unsigned integer large enough to store the uninterpreted bits of a pointer value
    

    当不同的数字类型混合在一个 表达式或赋值。

    Arithmetic operators

    <<   left shift             integer << unsigned integer
    >>   right shift            integer >> unsigned integer
    

    移位运算符将左操作数移位移位计数 由右操作数指定。他们实现算术移位,如果 左操作数是有符号整数,如果它是 无符号整数。班次计数没有上限。转移 表现得好像左操作数被移位 n 次 1 以进行移位 n个数因此,x > 1 是 与 x/2 相同,但被截断为负无穷。

    在 Go 中,它是一个无符号整数移位。 Go 有有符号和无符号整数。

    这取决于0xFF 的值是什么类型。假设它是无符号整数类型之一,例如uint

    package main
    
    import "fmt"
    
    func main() {
        n := uint(0xFF)
        fmt.Printf("%X\n", n)
        n = n >> 3
        fmt.Printf("%X\n", n)
    }
    

    输出:

    FF
    1F
    

    假设它是有符号整数类型之一,例如int

    package main
    
    import "fmt"
    
    func main() {
        n := int(0xFF)
        fmt.Printf("%X\n", n)
        n = int(uint(n) >> 3)
        fmt.Printf("%X\n", n)
    }
    

    输出:

    FF
    1F
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 2016-12-08
      • 2020-10-30
      相关资源
      最近更新 更多