Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string to specific type of int (int8, int16, int32, int64)

Tags:

go

I am trying to parse a string into an integer in Go. The Problem I found with it is in the documentation its mentioned syntax is as follows:

ParseInt(s string, base int, bitSize int) 

where, s is the string to be parsed, base is implied by the string's prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise.

The bitSize parameter is where I am facing problem. As per documentation of ParseInt, it 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.

But for all the values like 0, 8, 16, 32, and 64. I am getting same type return value. I.e of int64 type.

Could anyone point me out what am I missing.

Code: https://play.golang.org/p/F3LbUh_maY

like image 263
Amol M Kulkarni Avatar asked May 18 '15 09:05

Amol M Kulkarni


People also ask

What is the difference between int int16 int32 and int64?

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.

What is int64 data type?

Int64 is an immutable value type that represents signed integers with values that range from negative 9,223,372,036,854,775,808 (which is represented by the Int64. MinValue constant) through positive 9,223,372,036,854,775,807 (which is represented by the Int64. MaxValue constant.

Is int int64 in Golang?

int is one of the available numeric data types in Go used to store signed integers. int64 is a version of int that only stores signed numeric values composed of up to 64 bits.


1 Answers

As per documentation

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

ParseInt always return int64 no matter what. Moreover

The bitSize argument specifies the integer type that the result must fit into

So basically the your bitSize parameter only tells that the string value that you are going to parse should fit the bitSize after parsing. If not, out of range will happen.

Like in this PlayGround: strconv.ParseInt("192", 10, 8) (as you see the value after the parsing would be bigger than maximum value of int8).

If you want to parse it to whatever value you need, just use int8(i) afterwards (int8, int16, int32).

P.S. because you touched the topic how to convert to specific intX, I would outline that it is also possible to convert to unsigned int.

like image 58
Salvador Dali Avatar answered Oct 03 '22 13:10

Salvador Dali