douchenchepan6465 2016-09-12 01:09
浏览 1329
已采纳

在Golang中将int32转换为字符串

I need to convert an int32 to string in Golang. Is it possible to convert int32 to string in Golang without converting to int or int64 first?

Itoa needs an int. FormatInt needs an int64.

  • 写回答

3条回答 默认 最新

  • ds2128629 2016-09-12 05:46
    关注

    One line answer is fmt.Sprint(i).

    Anyway there are many conversions, even inside standard library function like fmt.Sprint(i), so you have some options (try The Go Playground):


    1- You may write your conversion function (Fastest):

    func String(n int32) string {
        buf := [11]byte{}
        pos := len(buf)
        i := int64(n)
        signed := i < 0
        if signed {
            i = -i
        }
        for {
            pos--
            buf[pos], i = '0'+byte(i%10), i/10
            if i == 0 {
                if signed {
                    pos--
                    buf[pos] = '-'
                }
                return string(buf[pos:])
            }
        }
    }
    

    2- You may use fmt.Sprint(i) (Slow)
    See inside:

    // Sprint formats using the default formats for its operands and returns the resulting string.
    // Spaces are added between operands when neither is a string.
    func Sprint(a ...interface{}) string {
        p := newPrinter()
        p.doPrint(a)
        s := string(p.buf)
        p.free()
        return s
    }
    

    3- You may use strconv.Itoa(int(i)) (Fast)
    See inside:

    // Itoa is shorthand for FormatInt(int64(i), 10).
    func Itoa(i int) string {
        return FormatInt(int64(i), 10)
    }
    

    4- You may use strconv.FormatInt(int64(i), 10) (Faster)
    See inside:

    // FormatInt returns the string representation of i in the given base,
    // for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z'
    // for digit values >= 10.
    func FormatInt(i int64, base int) string {
        _, s := formatBits(nil, uint64(i), base, i < 0, false)
        return s
    }
    

    Comparison & Benchmark (with 50000000 iterations):

    s = String(i)                       takes:  5.5923198s
    s = String2(i)                      takes:  5.5923199s
    s = strconv.FormatInt(int64(i), 10) takes:  5.9133382s
    s = strconv.Itoa(int(i))            takes:  5.9763418s
    s = fmt.Sprint(i)                   takes: 13.5697761s
    

    Code:

    package main
    
    import (
        "fmt"
        //"strconv"
        "time"
    )
    
    func main() {
        var s string
        i := int32(-2147483648)
        t := time.Now()
        for j := 0; j < 50000000; j++ {
            s = String(i) //5.5923198s
            //s = String2(i) //5.5923199s
            //s = strconv.FormatInt(int64(i), 10) // 5.9133382s
            //s = strconv.Itoa(int(i)) //5.9763418s
            //s = fmt.Sprint(i) // 13.5697761s
        }
        fmt.Println(time.Since(t))
        fmt.Println(s)
    }
    
    func String(n int32) string {
        buf := [11]byte{}
        pos := len(buf)
        i := int64(n)
        signed := i < 0
        if signed {
            i = -i
        }
        for {
            pos--
            buf[pos], i = '0'+byte(i%10), i/10
            if i == 0 {
                if signed {
                    pos--
                    buf[pos] = '-'
                }
                return string(buf[pos:])
            }
        }
    }
    
    func String2(n int32) string {
        buf := [11]byte{}
        pos := len(buf)
        i, q := int64(n), int64(0)
        signed := i < 0
        if signed {
            i = -i
        }
        for {
            pos--
            q = i / 10
            buf[pos], i = '0'+byte(i-10*q), q
            if i == 0 {
                if signed {
                    pos--
                    buf[pos] = '-'
                }
                return string(buf[pos:])
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵