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