Converting between strings and ascii integers

polaris · · 433 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I want to take the word &#34;Computer&#34; 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. </p> <hr/>**评论:**<br/><br/>planet12: <pre><p>You can loop over the characters using &#34;range&#34;, eg.</p> <pre><code>s := &#34;Computer&#34; for _, c := range s { fmt.Printf(&#34;c = %d (%c)\n&#34;, c, c) } </code></pre> <p>Output:</p> <pre><code>c = 67 (C) c = 111 (o) c = 109 (m) c = 112 (p) c = 117 (u) c = 116 (t) c = 101 (e) c = 113 (r) </code></pre> <p>Take a look at <a href="https://blog.golang.org/strings" rel="nofollow">https://blog.golang.org/strings</a></p></pre>chronokitsune3233: <pre><p>Another way to do it is to convert to <code>[]byte</code> (a slice of bytes):</p> <pre><code>func printBytes(s string) { sbytes := []byte(s) // You can also replace this with something like fmt.Printf(&#34;% x\n&#34;, sbytes) // if you want different output. fmt.Println(sbytes) } </code></pre> <p>If you want to print each byte individually along with the character it corresponds to, you might do something like this:</p> <pre><code>func printBytes(s string) { for i := 0; i &lt; len(s); i++ { fmt.Printf(&#34;Byte %3d: %3d %c\n&#34;, i, s[i], s[i]) } } </code></pre> <p>This differs from <code>for ... range s</code> subtly since a <code>range</code> over a string results in the runes of the string being looped over. For ASCII, it doesn&#39;t matter, but for all other characters (e.g. characters like <code>á</code>), <a href="https://play.golang.org/p/BGiufc52Jj" rel="nofollow">it matters</a>. Of course, if you have bytes in the string that don&#39;t form a valid UTF-8 sequence, the rune received for each &#34;bad&#34; byte would be the value of <a href="https://golang.org/pkg/unicode/#pkg-constants" rel="nofollow"><code>unicode.ReplacementChar</code></a>. You can find out more by reading <a href="https://blog.golang.org/strings" rel="nofollow">Strings, bytes, runes and characters in Go</a> as suggested in another comment.</p></pre>

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

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