Go program to convert a character to ASCII code and vice versa
2 minsASCII (American Standard Code for Information Exchange) is a character encoding standard used for representing text-based information with numbers. It is a 7-bit encoding scheme that contains encodings for a set of 128 characters. These characters include upper and lowercase alphabets (A-za-z
), digits (0-9
), special characters (e.g. [{}]%@
), and control characters (e.g. \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]