Created
May 3, 2013 20:39
-
-
Save jbuchbinder/5513891 to your computer and use it in GitHub Desktop.
Convert UTF-8 Go strings to ASCII bytes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"unicode/utf8" | |
) | |
// Fake converting UTF-8 internal string representation to standard | |
// ASCII bytes for serial connections. | |
func StringToAsciiBytes(s string) []byte { | |
t := make([]byte, utf8.RuneCountInString(s)) | |
i := 0 | |
for _, r := range s { | |
t[i] = byte(r) | |
i++ | |
} | |
return t | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This
StringToAsciiBytes
func is unfortunately just plain wrong. If you want to get hold of every byte of a Go string (which indeed is UTF-8)s
, then you just can just loop likefor _, b := range s
. Please read up what RuneCountInString does https://pkg.go.dev/unicode/utf8#RuneCountInString