我想转换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)
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我在分配后推迟类型转换,则代码可以解决。
package main
import (
"fmt"
)
func main() {
a := 0xfc
b := int8(a) // ok
fmt.Println(b)
}
Run Code Online (Sandbox Code Playgroud)
我的问题:
类型常量的值必须始终可以由常量类型的值准确表示。以下常量表达式是非法的:
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)
Run Code Online (Sandbox Code Playgroud)
并非所有整数值都可以适合所有整数类型。可能会出现两个问题:该值可能太大,或者可能是分配给无符号整数类型的负值。例如,int8的范围是-128到127,因此永远不能将超出该范围的常量分配给int8类型的变量:
var i8 int8 = 128 // Error: too large.
类似地,uint8(也称为字节)的范围是0到255,因此不能使用较大或负的常量被分配给一个uint8:
var u8 uint8 = -1 // Error: negative value.
这种类型检查可以捕获如下错误:Run Code Online (Sandbox Code Playgroud)type Char byte var c Char = '?' // Error: '?' has value 0x4e16, too large.如果编译器抱怨您使用常量,则可能是真正的错误。
我的实际需求的转换
byte,以int32解析二进制文件时。我可能会遇到常量字节0xfc,并应在考虑到符号的情况下int8将其转换为之前将其传输到int32。
是的,这是要走的路:
var b byte = 0xff
i32 := int32(int8(b))
fmt.Println(i32) // -1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
759 次 |
| 最近记录: |