string()做了我希望strconv.Itoa()会做的事情 [英] string() does what I hoped strconv.Itoa() would do

查看:72
本文介绍了string()做了我希望strconv.Itoa()会做的事情的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简短的程序,可以将一些二进制数字转换为与ASCII等价的数字.我尝试将其翻译成,发现 strconv.Itoa()无法正常工作.

I have a short program that converts a few binary numbers into their ASCII equivalents. I tried translating this into today and found that strconv.Itoa() doesn't work as I expected.

// translate Computer History Museum t-shirt
// http://i.ebayimg.com/images/g/qksAAOSwaB5XjsI1/s-l300.jpg

package main

import (
        "fmt"
        "strconv"
)

func main() {
        var binaryStrings [3]string
        binaryStrings = [3]string{"01000011","01001000","01001101"}

        for _,bin := range binaryStrings {
                if decimal, err := strconv.ParseInt(bin, 2, 64); err != nil {
                        fmt.Println(err)
                } else {
                        letter := strconv.Itoa(int(decimal))
                        fmt.Println(bin, decimal, letter, string(decimal))
                }
        }
}

输出

$ go run chm-tshirt.go 
01000011 67 67 C
01001000 72 72 H
01001101 77 77 M

所以看来 string()正在做我认为 strconv.Itoa()会做的事情.我期望第三列显示我在第四列中得到的结果.这是错误还是我想念什么?

So it seems like string() is doing what I thought strconv.Itoa() would do. I was expecting the third column to show what I get in the fourth column. Is this a bug or what am I missing?

推荐答案

strconv.Itoa 将整数格式化为十进制字符串.示例: strconv.Itoa(65) strconv.Itoa('A')返回字符串"65" .

string(intValue) 会产生一个包含UTF的字符串-8表示整数.示例: string('A') string(65)评估为字符串"A" .

经验表明,许多人错误地期望 string(intValue)返回整数值的十进制表示形式.由于这种期望如此普遍,因此当整数值的类型不是 rune 时, go vet 的Go 1.15版本会警告有关 string(intValue)转换.code>或 byte (在此处中阅读详细信息).

Experience has shown that many people erroneously expect string(intValue) to return the decimal representation of the integer value. Because this expectation is so common, the Go 1.15 version of go vet warns about string(intValue) conversions when the type of the integer value is not rune or byte (read details here).

这篇关于string()做了我希望strconv.Itoa()会做的事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆