gpt4 book ai didi

Go - 执行无符号移位操作

转载 作者:IT王子 更新时间:2023-10-29 01:59:15 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com