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:
chronokitsune3233: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
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 arange
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 ofunicode.ReplacementChar
. You can find out more by reading Strings, bytes, runes and characters in Go as suggested in another comment.
