Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ascii code to byte in golang?

Tags:

go

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

like image 397
zerozero7 Avatar asked Oct 28 '25 03:10

zerozero7


1 Answers

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
like image 182
maerics Avatar answered Oct 30 '25 14:10

maerics



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!