Go - 执行无符号移位操作

标签 go binary-operators

Go 中是否有执行无符号移位(即无符号右移)操作? Java 中是这样的

0xFF >>> 3

关于这个问题我能找到的唯一的就是这个post但我不确定我必须做什么。

提前致谢。

最佳答案

The Go Programming Language Specification

Numeric types

A numeric type represents sets of integer or floating-point values. The predeclared architecture-independent numeric types include:

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

The value of an n-bit integer is n bits wide and represented using two's complement arithmetic.

There is also a set of predeclared numeric types with implementation-specific sizes:

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

Conversions are required when different numeric types are mixed in an expression or assignment.

Arithmetic operators

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

The shift operators shift the left operand by the shift count specified by the right operand. They implement arithmetic shifts if the left operand is a signed integer and logical shifts if it is an unsigned integer. There is no upper limit on the shift count. Shifts behave as if the left operand is shifted n times by 1 for a shift count of n. As a result, x << 1 is the same as x*2 and x >> 1 is the same as x/2 but truncated towards negative infinity.

在 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

关于Go - 执行无符号移位操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33336336/

相关文章:

go - 两种不同语言之间的 Protocol Buffer

html - 如何使用 Revel Golang 处理来自 html 表单的动态输入数量

c - 简化 C 中的二进制 and 和 xor

python - Native Client (NaCl) 程序可以用 C 或 C++ 以外的语言编写吗?

Go - switch 语句中的重复大小写

c# - 线程安全左移

c# - 运算符 '<' 不能应用于类型 'long' 和 'ulong' 的操作数

java - 什么是 | Java 中的运算符在做什么?

firebase - Go SDK 上的 VerifyIDToken panic

haskell - haskell中什么是二元运算符