go - 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"
}
解决方案
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.
推荐阅读
- html - (Noob Question) Why is checking if the user is the author of a blog post completely different in .py and .html files?
- docker - Docker, Volumes vs Bind Mounts for persistent data such as DB, elasticsearch?
- c# - RectangleF 包含总是返回 false
- git - 无法使替换参考“永久”
- javascript - MongoConnect 作为回调传入客户端
- java - 通过单个端点将字符串数据和文件发送到基于 spring 的服务器
- angularjs - AngularJS UI 日历事件源未更新
- javascript - 如何循环通过使文本框可用于输入的 if 语句?
- python-3.x - Display image from url using holoviews
- sql - 解决 SUM 和 AVG,无法对包含聚合或子查询的表达式执行聚合函数