Integer Conversions Truncate And Wrap

Show what explicit conversions really do: int64 to int8 drops high bits, float to int truncates toward zero, and overflow wraps modulo the width.

GoData Integrity

Code

gosnippet
28 lines
package main

import (
	"fmt"
	"math"
)

func main() {
	// 显式转换:高位直接丢弃(按目标宽度截断)
	var big int64 = 0x1FF
	small := int8(big) // 0x1FF -> 0xFF,符号位为 1
	fmt.Println(big, "->", small, "truncated")

	// float 转 int:向零截断,小数部分直接丢弃
	fmt.Println(int(3.99), int(-3.99))

	// 溢出回绕:int8 加法结果按模 256 回绕
	var max int8 = 127
	fmt.Println("wrap:", max+1)

	// 超范围浮点转整型是未定义实现行为:先用范围检查守卫
	f := 1e10
	if f >= math.MinInt32 && f <= math.MaxInt32 {
		fmt.Println("in range:", int32(f))
	} else {
		fmt.Println("out of int32 range, refusing cast")
	}
}

How it works

Count the function main as the entire surface area of Integer Conversions Truncate And Wrap.

Using it

Running the file prints labeled results such as wrap:, in range:, out of int32 range, refusing cast — each operation’s effect is visible in the output.

Key statements

small := int8(big) // 0x1FF -> 0xFF,符号位为 1

Interactive Tools for This Topic

FAQ

What does Integer Conversions Truncate And Wrap print when run?
Run it as a complete program — the output lines carry labels such as `wrap:`, `in range:`, `out of int32 range, refusing cast`.