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
+32k Golang : Copy directory - including sub-directories and files
+7k Golang : Dealing with postal or zip code example
+5.5k Golang : Struct field tags and what is their purpose?
+6.9k Golang : Get environment variable
+7.3k Golang : Rename part of filename
+21.4k Golang : Upload big file (larger than 100MB) to AWS S3 with multipart upload
+5.5k Swift : Get substring with rangeOfString() function example
+23.8k Golang : Find biggest/largest number in array
+9.2k Golang : Qt Yes No and Quit message box example
+22.2k Golang : Convert Unix timestamp to UTC timestamp
+22.3k Golang : Set and Get HTTP request headers example
+14.5k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name