dongmai6666 2015-10-14 16:37
浏览 640
已采纳

在golang中将字符串转换为数字

Golang has strconv library that converts string to int64 and uint64.

However, the rest of integer data types seems to be unsupported as I can't find conversion functions for byte, int16, uint16, int32, uint32 data types.

One can always convert from byte, 16-bit and 32-bit data types to int64 and uint64 without loss of precision. Is that what's intended by language?

  • 写回答

3条回答 默认 最新

  • duanju7199 2015-10-14 16:41
    关注

    If you look at the docs a bit more closely you can use this method;

    func ParseInt(s string, base int, bitSize int)
    

    https://golang.org/pkg/strconv/#ParseInt

    The bitSize argument says how large the int is so you can do 8 or 16 or 32 for those smaller integer types. Atoi calls this internally. I believe you're wanting 10 for the base argument. So like b, err := strconv.ParseInt("5", 10, 8) for a byte.

    EDIT: Just going to add a couple things to the answer here in case the OP is in fact confused how to convert a 16-bit int into a string... If that is your intended goal just use fmt.Sprintf or you can do a conversion from smaller int to larger int as it will always succeed. Examples of both here; https://play.golang.org/p/UWSVxEmQ1N

    package main
    
    import "fmt"
    import "strconv"
    
    func main() {
        var a int16
        a = 5
        s := fmt.Sprintf("%d", a)
        s2 := strconv.Itoa(int(a))
        fmt.Println(s)
        fmt.Println(s2)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 有卷积神经网络识别害虫的项目吗
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件