Skip to content

Instantly share code, notes, and snippets.

@jbuchbinder
Created May 3, 2013 20:39
Show Gist options
  • Save jbuchbinder/5513891 to your computer and use it in GitHub Desktop.
Save jbuchbinder/5513891 to your computer and use it in GitHub Desktop.
Convert UTF-8 Go strings to ASCII bytes.
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
}
@inuoshios
Copy link

@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
}

@quite
Copy link

quite commented May 29, 2023

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

@inuoshios
Copy link

Thanks for the correction, @quite ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment