Parse Numbers With Base Zero Radix

Parse integers with ParseInt base 0 so 0x, 0o and 0b prefixes plus underscore separators pick their radix automatically and overflow surfaces as ErrRange.

GoConfig Management

Code

gosnippet
28 lines
package main

import (
	"fmt"
	"strconv"
)

func main() {
	// base 0:按前缀自动识别 radix,0x/0o/0b 与下划线分隔符都合法
	for _, raw := range []string{"0x1f", "0o17", "0b1011", "1_000", "15"} {
		v, err := strconv.ParseInt(raw, 0, 64)
		fmt.Printf("%-8s -> %d", raw, v)
		if err != nil {
			fmt.Printf("  err: %v", err)
		}
		fmt.Println()
	}

	// base 10 只认十进制:带前缀的输入直接报语法错误
	if _, err := strconv.ParseInt("0x1f", 10, 64); err != nil {
		numErr := err.(*strconv.NumError)
		fmt.Println("base 10 rejects 0x1f:", numErr.Err)
	}

	// 位宽限制:int8 放不下 300 时返回饱和边界值和 ErrRange
	v, err := strconv.ParseInt("300", 10, 8)
	fmt.Println("int8 300:", v, err)
}

What the code does

Count the function main as the entire surface area of Parse Numbers With Base Zero Radix.

The cycling part of this snippet is for _, raw := range []string{"0x1f", "0o17", "0b1011", "1_000", "15"}. Error handling is inline: 2 places test err != nil and branch immediately.

Using it

Running the file prints labeled results such as err:, base 10 rejects 0x1f:, int8 300: — each operation’s effect is visible in the output.

Key statements

for _, raw := range []string{"0x1f", "0o17", "0b1011", "1_000", "15"} {
	v, err := strconv.ParseInt(raw, 0, 64)
	fmt.Printf("%-8s -> %d", raw, v)
	if err != nil {
		fmt.Printf("  err: %v", err)
	}
	fmt.Println()
}

Interactive Tools for This Topic

FAQ

What does Parse Numbers With Base Zero Radix print when run?
The script runs standalone; its 3 labeled outputs include `err:`, `base 10 rejects 0x1f:`, `int8 300:`.