parsing an hex value with strconv

1,180 views
Skip to first unread message

Rodrigo Moraes

unread,
Feb 27, 2012, 11:30:05 AM2/27/12
to golang-nuts
Hey. With weekly.2012-02-22:

i, _ := strconv.ParseInt("FF", 16, 8) // 127
i, _ := strconv.ParseInt("FF", 16, 16) // 255

I'd expect that both would be 255. Why this happened?

-- rodrigo

minux

unread,
Feb 27, 2012, 11:47:35 AM2/27/12
to Rodrigo Moraes, golang-nuts
Because ParseInt parses *signed* numbers, and 8-bit signed integer could only represent
integers in range [-128, 127].

I think you really want strconv.ParseUint.

Rodrigo Moraes

unread,
Feb 27, 2012, 11:50:06 AM2/27/12
to golang-nuts
On Feb 27, 1:47 pm, minux wrote:
> Because ParseInt parses *signed* numbers, and 8-bit signed integer could
> only represent
> integers in range [-128, 127].
>
> I think you really want strconv.ParseUint.

Ah, doh, of course! Thank you. :)

-- rodrigo

Dustin

unread,
Feb 27, 2012, 11:52:02 AM2/27/12
to golan...@googlegroups.com
According to the docs:

"The bitSize argument 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."

255 isn't a valid 8 bit signed integer.  I would expect -1.

minux

unread,
Feb 27, 2012, 12:01:47 PM2/27/12
to Dustin, golan...@googlegroups.com
It's out of range, so ErrRange is returned, and the document doesn't say anything about
the value returned when error occurred.

Dustin

unread,
Feb 27, 2012, 1:19:53 PM2/27/12
to golan...@googlegroups.com, Dustin

On Monday, February 27, 2012 9:01:47 AM UTC-8, minux wrote:
255 isn't a valid 8 bit signed integer.  I would expect -1.
It's out of range, so ErrRange is returned, and the document doesn't say anything about
the value returned when error occurred.

That's an excellent point (always check the error).  I was looking at 0xFF as eight one bits, which is -1.  I guess I could argue with the parser as to which makes more sense, but I'll let it win.

Reply all
Reply to author
Forward
0 new messages