duanpi7107 2019-04-17 04:19
浏览 1200
已采纳

关于将uint8转换为int8的困惑

I want to convert uint8 to int, so I write a const 0xfc, and try to use int8(0xfc) to convert it. However the code raises an error:

package main

import (
    "fmt"
)

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

But if I defer the type conversion after assignment, the code can work around.

package main

import (
    "fmt"
)

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

My question:

  • Is there any difference between these two codes?
  • Why does the first one raise a compile error?
  • 写回答

2条回答 默认 最新

  • dongxie2749 2019-04-17 04:32
    关注
    1. see: 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. see: 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.

    Yes, this is the way to go:

    
        var b byte = 0xff
        i32 := int32(int8(b))
        fmt.Println(i32) // -1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)