I have a string containing an integer (which has been read from a file).
I'm trying to convert the string
to an int
using strconv.ParseInt()
. ParseInt
requires that I provide a bitsize (bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64).
The integer read from the file is small (i.e. it should fit in a normal int). If I pass a bitsize of 0, however, I get a result of type int64
(presumably because I'm running on a 64-bit OS).
Why is this happening? How do I just get a normal int? (If someone has a quick primer on when and why I should use the different int types, that would awesome!)
Edit: I can convert the int64 to a normal int using int([i64_var])
. But I still don't understand why ParseInt()
is giving me an int64 when I'm requesting a bitsize of 0.
"In practice, Go usually uses int64 for int on an amd64 [..]" - more precisely, int always equals the processor bit-size. So on 64 bit systems, it's 64 bit, on 32bit systems, it's 32 bit.
1. Int16 is used to represents 16-bit signed integers. Int32 is used to represents 32-bit signed integers . Int64 is used to represents 64-bit signed integers.
Use int64 and friends for data The types int8 , int16 , int32 , and int64 (and their unsigned counterparts) are best suited for data. An int64 is the typical choice when memory isn't an issue. In particular, you can use a byte , which is an alias for uint8 , to be extra clear about your intent.
int is one of the available numeric data types in Go . int has a platform-dependent size, as, on a 32-bit system, it holds a 32 bit signed integer, while on a 64-bit system, it holds a 64-bit signed integer.
func ParseInt(s string, base int, bitSize int) (i int64, err error)
ParseInt always returns int64
bitSize
defines range of values. If the value corresponding to s cannot be represented by a signed integer of the given size, err.Err = ErrRange.
http://golang.org/pkg/strconv/#ParseInt
type int int
int is a signed integer type that is at least 32 bits in size. It is a distinct type, however, and not an alias for, say, int32.
http://golang.org/pkg/builtin/#int
So int
could be bigger than 32 bit in future or on some systems like int
in C.
I guess on some systems int64
might be faster than int32
because that system only works with 64 bit integers.
Here is example of error when bitSize
is 8
http://play.golang.org/p/_osjMqL6Nj
package main import ( "fmt" "strconv" ) func main() { i, err := strconv.ParseInt("123456", 10, 8) fmt.Println(i, err) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With