无论如何在 Go 中执行无符号移位(即无符号右移)操作?Java中类似的东西
0xFF >>> 3
在这件事上我唯一能找到的就是这篇文章,但我不确定我必须做什么。
提前致谢。
数字类型表示整数或浮点值的集合。预先声明的独立于体系结构的数字类型包括:
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
当表达式或赋值中混合了不同的数值类型时,需要进行转换。
<< left shift integer << unsigned integer >> right shift integer >> unsigned integer
移位运算符将左操作数移位右操作数指定的移位计数。如果左操作数是有符号整数,它们实现算术移位,如果它是无符号整数,它们实现逻辑移位。班次计数没有上限。移位的行为就好像左操作数被移位 n 次,移位计数为 n。结果,x << 1 与 x*2 相同,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