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
+13.8k Golang : Human readable time elapsed format such as 5 days ago
+34.6k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+9.3k Android Studio : Indicate progression with ProgressBar example
+9.3k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+48k Golang : How to convert JSON string to map and slice
+14.4k Android Studio : Use image as AlertDialog title with custom layout example
+29.5k Golang : Record voice(audio) from microphone to .WAV file
+7.6k Golang : Command line ticker to show work in progress
+5k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version
+16.7k Golang : Gzip file example
+22.1k Golang : How to run Golang application such as web server in the background or as daemon?
+4.9k Golang : micron to centimeter example