How to Convert ASCII to Rune in Golang

To convert an ASCII to Rune in Go, use the “string()” function. Rune slice is re-grouping of byte slice so that each index is a character.

ASCII is a character encoding standard for representing text-based information with numbers. ASCII is a code that contains 128 characters with integer values from 0 to 127. It can be stored in 8-bit types.

Rune represents a Unicode code point and has the type alias rune for the int32 data type.

Example 1

package main

import (
  "fmt"
)

func main() {
   ascii := 75 //
   rn := string(ascii)
   fmt.Printf("%d character is : %s\n", ascii, rn)
}

Output

75 character is : K

We assigned an ascii code point 75, the Rune “K”. To convert a code point to a rune, we used a string() function and passed the ascii code to it. It returns the character code “K” for the ascii code 75.

Example 2

package main

import "fmt"

func main() {
  // Example: 1
  str := "MOJO"
  runes := []rune(str)

  var result []int

  for i := 0; i < len(runes); i++ {
    result = append(result, int(runes[i]))
  }

  fmt.Println(result)

  // Example: 2
  s := "MOJO"
  for _, r := range s {
    fmt.Printf("%c - %d\n", r, r)
  }
}

Output

[77 79 74 79]

M - 77
O - 79
J - 74
O - 79

That’s it.