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

关于将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 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web