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 | |
} |
@nerotiger to convert to string, I think you can do something like this since strings default encoding is UTF-8
package main
import "fmt"
func main() {
stringToAscii := StringToAsciiBytes("hello")
fmt.Println(stringToAscii ) // this will print out [104 101 108 108 111]
// To convert back to string, you can do something like
asciiBytesToString = string(stringToAscii )
fmt.Println(asciiBytesToString) // this will print out hello
}
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 like for _, b := range s
. Please read up what RuneCountInString does https://pkg.go.dev/unicode/utf8#RuneCountInString
Thanks for the correction, @quite ❤️
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to do then change the ASCII back to UTF8