首页 > 解决方案 > Arithmetic on uint8, int8

问题描述

What is the reason for getting negative and zero results in the Arithmetic operation on unit8 and int8 data types for the given example

package main

import (
    "fmt"
)

func main() {

     var u uint8 = 255
     fmt.Println(u, u+1, u*u) // "255 0 1"
     var i int8 = 127
     fmt.Println(i, i+1, i*i) // "127 -128 1"
}

https://play.golang.org/p/_a2KHP29t5p

标签: goint

解决方案


Go does not panic for integer overflow in runtime. As per doc:

For unsigned integer values, the operations +, -, *, and << are computed modulo 2n, where n is the bit width of the unsigned integer's type. Loosely speaking, these unsigned integer operations discard high bits upon overflow, and programs may rely on "wrap around".

For signed integers, the operations +, -, *, /, and << may legally overflow and the resulting value exists and is deterministically defined by the signed integer representation, the operation, and its operands. No exception is raised as a result of overflow. A compiler may not optimize code under the assumption that overflow does not occur. For instance, it may not assume that x < x + 1 is always true.


推荐阅读