dpy33121 2015-05-18 09:35
浏览 335
已采纳

将字符串解析为int的特定类型(int8,int16,int32,int64)

I am trying to parse a string into an integer in Go. The Problem I found with it is in the documentation its mentioned syntax is as follows:

ParseInt(s string, base int, bitSize int)

where, s is the string to be parsed, base is implied by the string's prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise.

The bitSize parameter is where I am facing problem. As per documentation of ParseInt, it 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.

But for all the values like 0, 8, 16, 32, and 64. I am getting same type return value. I.e of int64 type.

Could anyone point me out what am I missing.

Code: https://play.golang.org/p/F3LbUh_maY

  • 写回答

3条回答 默认 最新

  • dongyuan8312 2015-05-18 09:47
    关注

    As per documentation

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

    ParseInt always return int64 no matter what. Moreover

    The bitSize argument specifies the integer type that the result must fit into

    So basically the your bitSize parameter only tells that the string value that you are going to parse should fit the bitSize after parsing. If not, out of range will happen.

    Like in this <kbd>PlayGround</kbd>: strconv.ParseInt("192", 10, 8) (as you see the value after the parsing would be bigger than maximum value of int8).

    If you want to parse it to whatever value you need, just use int8(i) afterwards (int8, int16, int32).

    P.S. because you touched the topic how to convert to specific intX, I would outline that it is also possible to convert to unsigned int.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False