dongni8124 2016-03-07 18:35
浏览 127
已采纳

Golang:解析一个有符号的int

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?

  • 写回答

1条回答 默认 最新

  • dongnaigu2052 2016-03-07 18:40
    关注

    For example,

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

    Output:

    ff11223344556677 <nil>
    -67234915848722825
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?