Golang ASCII to Rune: How to Convert Code Point to Char

Working with data in Golang, you’ll often need to convert between various data types. One standard conversion is between ASCII characters and their numeric values.

What is ASCII in Go?

ASCII in Golang is a character encoding standard used 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.

There is no character type in Go, but it has a rune data type that you can represent. Each character contains integer code which is called ASCII code.

What is Rune in Go?

Rune in Golang is represented as one or more characters in quotes like “k”. A character is defined using “code points” in Unicode. For ASCII characters, the rune value will be the same as the byte value.

Golang ASCII to Rune

To convert an ASCII to Rune in Golang, use the string() function. Rune slice is re-grouping of byte slice so that each index is a character. A rune slice appends and modifies characters with no errors.

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

To get the ASCII value of a character, create an integer with a character assigned to the integer, and the Go compiler converts a character value to ASCII code.

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.

That’s it.

Leave a Comment