douzhi4830 2013-12-02 04:44
浏览 68
已采纳

将长字符串转换为int64-Go

I am finding the way to cast an integer number in a long string format to int64 in Go. I used strconv.Atoi but it gave me an error said "value out of range". I searched for the answer I found

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

in strconv package. However, I don't understand what value should I provide for the function arguments including base and bitSize.

I am trying to parse datastore.Key.IntID() in string format that I received from HTTP request back to int64 for creating new keys to perform query on Datastore.

Could anyone explain me a bit about the base and bitSize arguments and what values should I provide in the arguments in this case?

  • 写回答

1条回答 默认 最新

  • dougu2240 2013-12-02 04:59
    关注

    func ParseInt

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

    ParseInt interprets a string s in the given base (2 to 36) and returns the corresponding value i. If base == 0, the base is implied by the string's prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise.

    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.

    The errors that ParseInt returns have concrete type *NumError and include err.Num = s. If s is empty or contains invalid digits, err.Err = ErrSyntax; if the value corresponding to s cannot be represented by a signed integer of the given size, err.Err = ErrRange.

    For example,

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func main() {
        s := "9223372036854775807"
        i, err := strconv.ParseInt(s, 10, 64)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(i)
    }
    

    Output:

    9223372036854775807
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?