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.
Code
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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.