How to Convert Rune to ASCII in Golang

To convert a Rune to ASCII in Golang, you can cast a rune to a byte using the “byte()” function and then use the “string()” function to convert it to a string.

Example

package main

import "fmt"

func main() {
  r := 'A'

  // Check if the rune is an ASCII character
  if r >= 0 && r <= 127 {
    ascii := string(byte(r))
    fmt.Println("Rune as ASCII:", ascii)
  } else {
    fmt.Println("The rune is not an ASCII character")
  }
}

Output

Rune as ASCII: A

In this code snippet, we checked if the rune r is within the ASCII range (0 to 127). If it is, we cast it to a byte and then convert the byte to a string using the “string()” function.

The resulting ASCII representation is then printed to the console.

Leave a Comment