Home > Software engineering >  Converting Hex to signed Int in Go
Converting Hex to signed Int in Go

Time:05-10

I want to convert a hex string to a signed integer Value in Go. My input value is "FF60" and I want the output to be "-160". When I use the following function, the result is "65376", which represents the unsigned representation.

value, err := strconv.ParseInt("FF60", 16, 64)

I would have expected the outcome of 65376 when using the ParseUInt function. Any help would be really appreciated.

CodePudding user response:

The third parameter of strconv.ParseInt() tells the bitsize of the integer you want to parse. 0xff60 parsed as a 64-bit integer is indeed 65376.

You actually want to parse it as a 16-bit integer, so pass 16 as the bitsize. Doing so you will get an error though:

strconv.ParseInt: parsing "FF60": value out of range

Which is true: 0xFF60 (which is 65376) is outside of the valid range of int16 (valid int16 range is [-32768..32767]).

So what you may do is parse it as an unsigned 16-bit integer using strconv.ParseUint(), then convert the result to a signed 16-bit integer:

value, err := strconv.ParseUint("FF60", 16, 16)
fmt.Println(value, err)
fmt.Println(int16(value))

This will output (try it on the Go Playground):

65376 <nil>
-160
  • Related