zerozero7
zerozero7

Reputation: 433

How to convert ascii code to byte in golang?

As the title say, I can find the function to give me ascii code of bytes, but not the other way around

Upvotes: 4

Views: 23280

Answers (1)

maerics
maerics

Reputation: 156434

Golang string literals are UTF-8 and since ASCII is a subset of UTF-8, and each of its characters are only 7 bits, we can easily get them as bytes by casting (e.g. bytes := []byte(str):

package main

import "fmt"

func main() {
  asciiStr := "ABC"
  asciiBytes := []byte(asciiStr)

  fmt.Printf("OK: string=%v, bytes=%v\n", asciiStr, asciiBytes)
  fmt.Printf("OK: byte(A)=%v\n", asciiBytes[0])
}
// OK: string=ABC, bytes=[65 66 67]
// OK: byte(A)=65

Upvotes: 8

Related Questions