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
+6.3k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+18.6k Golang : Example for RSA package functions
+27k Golang : Find files by extension
+11k Golang : Removes punctuation or defined delimiter from the user's input
+24.7k Golang : How to validate URL the right way
+5.9k Linux/Unix/PHP : Restart PHP-FPM
+5.6k Golang : Display advertisement images or strings on random order
+7.7k Golang : Dealing with struct's private part
+20k Golang : Measure http.Get() execution time
+33.8k Golang : How to check if slice or array is empty?
+7.4k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+19.6k Golang : How to Set or Add Header http.ResponseWriter?