duanchong3075 2016-08-30 19:28
浏览 68
已采纳

string()做我希望strconv.Itoa()会做的事情

I have a short program that converts a few binary numbers into their ASCII equivalents. I tried translating this into go 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))
                }
        }
}

which outputs

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

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?

  • 写回答

1条回答 默认 最新

  • dongpan2788 2016-08-30 19:40
    关注

    strconv.Itoa formats an integer as a decimal string. Example: strconv.Itoa(65) and strconv.Itoa('A') return the string "65".

    string(intValue) yields a string containing the UTF-8 representation of the integer. Example: string('A') and string(65) evaluate to the string "A".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案