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.
Code
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
Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.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.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.