go ParseInt()方法

ParseInt()语法

func ParseInt(s string, base int, bitSize int) (i int64, err error)

go源码中对ParseInt()方法的介绍:

ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.

If the base argument is 0, the true base is implied by the string's prefix: 2 for "0b", 8 for "0" or "0o", 16 for "0x", and 10 otherwise. Also, for argument base 0 only, underscore characters are permitted as defined by the Go syntax for integer literals.
The bitSize argument specifies the integer type that the result must fit into. Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64. If bitSize is below 0 or above 64, an error is returned.

The errors that ParseInt returns have concrete type *NumError and include err.Num = s. If s is empty or contains invalid digits, err.Err = ErrSyntax and the returned value is 0; if the value corresponding to s cannot be represented by a signed integer of the given size, err.Err = ErrRange and the returned value is the maximum magnitude integer of the appropriate bitSize and sign.

即,go中的strconv模块的ParseInt()方法,可以将一个字符串根据参数base和baseSize转换为int类型的数值。


参数

参数描述
sgo string字符串类型
basego int类型,指定进制,范围为0至36,如果base为0,则会根据字符串的前缀进行相应的判断,比如“0x”前缀的是16进制,“0”的是8进制,否则默认为十进制。
bitSizego int类型,指定返回值结果适合的整数类型,比如 0, 8, 16, 32, and 64 对应的是int, int8, int16, int32, and int64

返回值

strconv.PareseInt()的返回值有两个类型,分别为转换的值和err,其中err默认为*NumErr类型的,若语法的问题,则为ErrSyntax;若超出类型范围,则为ErrRange。


strconv.PareseInt()实例代码

func main() {
	i, e := strconv.ParseInt("FF", 16, 0)
	if e == nil {
		fmt.Println(i)
	}
}

运行go文件,得到输出:

255

全栈后端 / go语法 :













Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.