How to convert a string or char to ASCII code in Golang

ASCII (American Standard Code for Information Exchange) is a character encoding standard used for representing text-based information with numbers. It encodes 128 specified characters into 7-bit integers. These characters include Alphabets (A-za-z), digits (0-9), special characters ([{}]%@), and control characters (\r, \n).

This article shows you how to convert (encode) a character to an ASCII code and vice versa in Golang.

The conversion from ascii code to character or character to ascii code is done using type casting. Check out the following programs to understand how it works:

Convert character to ASCII Code in Go

package main

import "fmt"

func main() {
	c := 'A' // rune (characters in Go are represented using `rune` data type)
	asciiValue := int(c)

	fmt.Printf("Ascii Value of %c = %d\n", c, asciiValue)
}
$ go run ascii_to_char.go
Ascii Value of A = 65

Convert ASCII code to character in Go

package main

import "fmt"

func main() {
	asciiValue := 97
	character := rune(asciiValue)

	fmt.Printf("Character corresponding to Ascii Code %d = %c\n", asciiValue, character)
}
$ go run char_to_ascii.go
Character corresponding to Ascii Code 97 = a

Convert a string to a list of ASCII values in Go

package main

import "fmt"

func main() {
	str := "GOLANG"
	runes := []rune(str)

	var result []int

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

	fmt.Println(result)
}
$ go run string_to_ascii.go
[71 79 76 65 78 71]

Learn more