Golang : How to convert character to ASCII and back
Problem:
ASCII or American Standard Code for Information Interchange is used to represent characters and device control in computers. How to convert a character to ASCII and back to a character?
Solution:
To get the ASCII value of a character, simply type cast the character with int()
function and make sure the character is a rune
instead of type string
. To revert it back or to convert integer ASCII value to a character, type cast the integer with string()
function.
Here you go!
package main
import (
"fmt"
)
func main() {
// character to ASCII
char := 'a' // rune, not string
ascii := int(char)
fmt.Println(string(char), " : ", ascii)
// ASCII to character
asciiNum := 65 // Uppercase A
character := string(asciiNum)
fmt.Println(asciiNum, " : ", character)
}
Output:
a : 97
65 : A
Reference:
See also : Golang : Get ASCII code from a key press(cross-platform) example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+19.7k Golang : Get current URL example
+7.6k Golang : Shuffle strings array
+15k Golang : Basic authentication with .htpasswd file
+18.8k Golang : convert int to string
+14.4k Golang : How to shuffle elements in array or slice?
+6.7k Golang : Warp text string by number of characters or runes example
+14k Golang : How to check if a file is hidden?
+10.7k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+6.4k WARNING: UNPROTECTED PRIVATE KEY FILE! error message
+16.5k Golang : Check if a string contains multiple sub-strings in []string?
+9k Golang : Accept any number of function arguments with three dots(...)
+36.5k Golang : How to split or chunking a file to smaller pieces?