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
+46.7k Golang : Marshal and unmarshal json.RawMessage struct example
+4.7k MariaDB/MySQL : How to get version information
+15k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+7.2k Golang : Gorrila mux.Vars() function example
+13.5k Golang : Linear algebra and matrix calculation example
+29.6k Golang : How to create new XML file ?
+12.8k Golang : Remove or trim extra comma from CSV
+30.7k Golang : Remove characters from string example
+7.4k Golang : Not able to grep log.Println() output
+9.9k Golang : Format strings to SEO friendly URL example
+6.6k Unix/Linux : How to get own IP address ?
+19.4k Golang : Get RGBA values of each image pixel