duanpi7107 2019-04-17 04:19
浏览 1197


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 (

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

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

package main

import (

func main() {
    a := 0xfc
    b := int8(a)  // ok

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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 PdfiumViewer pdf转图片
  • ¥15 利用Java连接API接口总是出问题
  • ¥15 请教一个关于镜头标定,棋盘格格子大小的问题(畸变测试)
  • ¥15 安装GroudingDINO RuntimeError: Error compiling objects for extension
  • ¥15 关于推送项目到github的问题
  • ¥15 急!C++指针编写相关的问题
  • ¥15 kerberos身份认证配置问题
  • ¥30 用python写一个多签情况下波场的代理资源和回收资源
  • ¥15 matlab学期例题代码答疑
  • ¥15 在线手电筒追加按钮JS