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
+3.4k Javascript : How to show different content with noscript?
+10.4k Golang : Verify Linux user password again before executing a program example
+13.9k Golang : Get digits from integer before and after given position example
+11.6k Python : Convert IPv6 address to decimal and back to IPv6
+12.7k Golang: Pad right or print ending(suffix) zero or spaces in fmt.Printf example
+19.8k Golang : Sort and reverse sort a slice of strings
+10.3k Golang : Generate DSA private, public key and PEM files example
+6.5k Gogland : Single File versus Go Application Run Configurations
+19.8k Golang : How to get time zone and load different time zone?
+5.9k Golang : How to detect if a sentence ends with a punctuation?
+8.2k Golang : does not implement flag.Value (missing Set method)
+3.7k Linux/MacOSX : How to symlink a file?