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
+5.3k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+3.4k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+12.1k Golang : How to read JPG(JPEG), GIF and PNG files ?
+3.3k Golang : How to check variable or object type during runtime?
+5.9k Facebook : Getting the friends list with PHP return JSON format
+6.3k Golang : Read file and convert content to string
+3.4k Golang : Rename part of filename
+3.2k Golang : ROT47 (Caesar cipher by 47 characters) example
+9.6k Golang : Compare floating-point numbers
+5.6k Golang : Get all local users and print out their home directory, description and group id
+15.1k Golang : Get file last modified date and time