2015-10-14 16:37
浏览 563


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?

图片转代码服务由CSDN问答提供 功能建议

Golang具有 strconv 库,可将字符串转换为int64和uint64。

但是,由于我找不到字节的转换函数,其余的整数数据类型似乎不受支持 ,int16,uint16,int32,uint32数据类型。

始终可以将字节,16位和32位数据类型转换为int64和uint64,而不会损失精度。 那是语言的意图吗?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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)

    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;

    package main
    import "fmt"
    import "strconv"
    func main() {
        var a int16
        a = 5
        s := fmt.Sprintf("%d", a)
        s2 := strconv.Itoa(int(a))
    解决 无用
    打赏 举报
  • 查看更多回答(2条)

相关推荐 更多相似问题