golang ParseInt int8 不是无符号的

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

golang ParseInt int8 is not unsigned

问题

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

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

返回127

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

返回正确的数字248

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

英文:

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

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

return 127

  1. 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

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

例如,

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. func main() {
  7. // +127
  8. i, err := strconv.ParseInt("01111111", 2, 8)
  9. if err != nil {
  10. fmt.Println(err)
  11. }
  12. fmt.Println(i)
  13. // -128
  14. i, err = strconv.ParseInt("-10000000", 2, 8)
  15. if err != nil {
  16. fmt.Println(err)
  17. }
  18. fmt.Println(i)
  19. // +248 超出int8范围
  20. i, err = strconv.ParseInt("11111000", 2, 8)
  21. if err != nil {
  22. fmt.Println(err)
  23. }
  24. fmt.Println(i)
  25. // 无符号的248在uint8(字节)范围内
  26. u, err := strconv.ParseUint("11111000", 2, 8)
  27. if err != nil {
  28. fmt.Println(err)
  29. }
  30. fmt.Println(u)
  31. }

输出:

  1. 127
  2. -128
  3. strconv.ParseInt: parsing "11111000": value out of range
  4. 127
  5. 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,

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. func main() {
  7. // +127
  8. i, err := strconv.ParseInt("01111111", 2, 8)
  9. if err != nil {
  10. fmt.Println(err)
  11. }
  12. fmt.Println(i)
  13. // -128
  14. i, err = strconv.ParseInt("-10000000", 2, 8)
  15. if err != nil {
  16. fmt.Println(err)
  17. }
  18. fmt.Println(i)
  19. // +248 out of range for int8
  20. i, err = strconv.ParseInt("11111000", 2, 8)
  21. if err != nil {
  22. fmt.Println(err)
  23. }
  24. fmt.Println(i)
  25. // unsigned 248 in range for uint8 (byte)
  26. u, err := strconv.ParseUint("11111000", 2, 8)
  27. if err != nil {
  28. fmt.Println(err)
  29. }
  30. fmt.Println(u)
  31. }

Output:

  1. 127
  2. -128
  3. strconv.ParseInt: parsing "11111000": value out of range
  4. 127
  5. 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:

确定