golang ParseInt int8 不是无符号的

huangapple go评论76阅读模式
英文:

golang ParseInt int8 is not unsigned

问题

尝试将8位二进制字符串转换为字节(无符号)

strconv.ParseInt("11111000", 2, 8)

返回127

strconv.ParseInt("11111000", 2, 16)

返回正确的数字248

根据ParseInt文档,8代表int8,范围为-128到127。那么为什么返回值不是一个负数呢?

英文:

Try to turn 8-bit binary string into a byte (unsigned)

strconv.ParseInt("11111000", 2, 8)

return 127

strconv.ParseInt("11111000", 2, 16)

returns the correct number 248

According to ParseInt document, 8 stands for int8, which goes -128 to 127. If so, why not the return value be a negative number?

答案1

得分: 3

你解析正有符号整数,负有符号整数前缀为减号。对于无符号整数,解析为无符号。此外,始终检查错误。

例如,

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// +127
	i, err := strconv.ParseInt("01111111", 2, 8)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)
	// -128
	i, err = strconv.ParseInt("-10000000", 2, 8)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)
	// +248 超出int8范围
	i, err = strconv.ParseInt("11111000", 2, 8)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)
	// 无符号的248在uint8(字节)范围内
	u, err := strconv.ParseUint("11111000", 2, 8)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(u)
}

输出:

127
-128
strconv.ParseInt: parsing "11111000": value out of range
127
248
英文:

You parse positive signed integers, negative signed integers are prefixed with a minus sign. For unsigned integers, parse as unsigned. Also, always check for errors.

For example,

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// +127
	i, err := strconv.ParseInt("01111111", 2, 8)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)
	// -128
	i, err = strconv.ParseInt("-10000000", 2, 8)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)
	// +248 out of range for int8
	i, err = strconv.ParseInt("11111000", 2, 8)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)
	// unsigned 248 in range for uint8 (byte)
	u, err := strconv.ParseUint("11111000", 2, 8)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(u)
}

Output:

127
-128
strconv.ParseInt: parsing "11111000": value out of range
127
248

答案2

得分: 0

ParseInt将过大的值截断为该数据类型的最大值。如果您检查第二个返回值(错误代码),您会发现它返回了一个范围错误。

英文:

ParseInt clamps values that are too large to the maximum for the datatype. If you check the second return value (the error code), you'll see that it's returned a range error.

huangapple
  • 本文由 发表于 2013年6月24日 01:33:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/17263417.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定