Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: parse a signed int

Tags:

go

I have some code that needs to be able to parse a string containing a 64-bit value into an int64. For example, ff11223344556677 is valid, but a downstream system wants that in an int64.

strconv.ParseInt("ff11223344556677", 16, 64) gives a range error - it only likes to parse positive integers. Is there a way to go about putting this value into an int64 even though it is going to be negative?

like image 830
Chris Adams Avatar asked Oct 17 '25 10:10

Chris Adams


1 Answers

For example,

package main

import (
    "fmt"
    "strconv"
)

func main() {
    u, err := strconv.ParseUint("ff11223344556677", 16, 64)
    fmt.Printf("%x %v\n", u, err)
    i := int64(u)
    fmt.Println(i)
}

Output:

ff11223344556677 <nil>
-67234915848722825
like image 170
peterSO Avatar answered Oct 18 '25 23:10

peterSO