gpt4 book ai didi

go - 关于将 `uint8` 转换为 `int8` 的困惑

转载 作者:IT王子 更新时间:2023-10-29 00:38:14 26 4
gpt4 key购买 nike

我想将uint8转换成int,所以我写了一个const 0xfc,并尝试使用int8(0xfc) 进行转换。但是代码会引发错误:

package main

import (
"fmt"
)

func main() {
a := int8(0xfc) // compile error: constant 252 overflows int8
b := a
fmt.Println(b)
}

但如果我在赋值后推迟类型转换,代码就可以变通。

package main

import (
"fmt"
)

func main() {
a := 0xfc
b := int8(a) // ok
fmt.Println(b)
}

我的问题:

  • 这两个代码有什么区别吗?
  • 为什么第一个会引发编译错误?

最佳答案

  1. 参见:https://golang.org/ref/spec#Constant_expressions

The values of typed constants must always be accurately representable by values of the constant type. The following constant expressions are illegal:

uint(-1)     // -1 cannot be represented as a uint
int(3.14) // 3.14 cannot be represented as an int
int64(Huge) // 1267650600228229401496703205376 cannot be represented as an int64
Four * 300 // operand 300 cannot be represented as an int8 (type of Four)
Four * 100 // product 400 cannot be represented as an int8 (type of Four)
  1. 查看: https://blog.golang.org/constants

not all integer values can fit in all integer types. There are two problems that might arise: the value might be too large, or it might be a negative value being assigned to an unsigned integer type. For instance, int8 has range -128 through 127, so constants outside of that range can never be assigned to a variable of type int8:
var i8 int8 = 128 // Error: too large.
Similarly, uint8, also known as byte, has range 0 through 255, so a large or negative constant cannot be assigned to a uint8:
var u8 uint8 = -1 // Error: negative value.
This type-checking can catch mistakes like this one:

    type Char byte
var c Char = '世' // Error: '世' has value 0x4e16, too large.

If the compiler complains about your use of a constant, it's likely a real bug like this.


My actual demand is to convert a byte to int32 when parsing a binary file. I may encounter the constant byte 0xfc, and should transfer it to the int8 before converting it to the int32 with the consideration of sign.

是的,这是要走的路:


var b byte = 0xff
i32 := int32(int8(b))
fmt.Println(i32) // -1

关于go - 关于将 `uint8` 转换为 `int8` 的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55719813/

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