Converting between strings and ascii integers

polaris · 2017-05-19 16:00:02 · 670 次点击    
这是一个分享于 2017-05-19 16:00:02 的资源,其中的信息可能已经有所发展或是发生改变。

I want to take the word "Computer" and produce 8 numbers representing the ascii integers. I just started learning golang and only know the very basics (functions, arrays, loops) so the more elementary the better.


评论:

planet12:

You can loop over the characters using "range", eg.

s := "Computer"
for _, c := range s {
    fmt.Printf("c = %d (%c)\n", c, c)
}

Output:

c = 67 (C)
c = 111 (o)
c = 109 (m)
c = 112 (p)
c = 117 (u)
c = 116 (t)
c = 101 (e)
c = 113 (r)

Take a look at https://blog.golang.org/strings

chronokitsune3233:

Another way to do it is to convert to []byte (a slice of bytes):

func printBytes(s string) {
    sbytes := []byte(s)
    // You can also replace this with something like fmt.Printf("% x\n", sbytes)
    // if you want different output.
    fmt.Println(sbytes)
}

If you want to print each byte individually along with the character it corresponds to, you might do something like this:

func printBytes(s string) {
    for i := 0; i < len(s); i++ {
        fmt.Printf("Byte %3d: %3d %c\n", i, s[i], s[i])
    }
}

This differs from for ... range s subtly since a range over a string results in the runes of the string being looped over. For ASCII, it doesn't matter, but for all other characters (e.g. characters like á), it matters. Of course, if you have bytes in the string that don't form a valid UTF-8 sequence, the rune received for each "bad" byte would be the value of unicode.ReplacementChar. You can find out more by reading Strings, bytes, runes and characters in Go as suggested in another comment.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

670 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传