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.1k Golang : Get missing location after unmarshal binary and gob decode time.
+14.5k Golang : Loop each day of the current month example
+14.9k Golang : Read integer from file into array
+7.6k Golang : Convert(cast) []byte to io.Reader type
+4.9k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+16.1k Golang : How to make a file read only and set it to writable again?
+12.1k Golang : How to get a user home directory path?
+3.9k Javascript : How to get width and height of a div?
+6k Linux : How to fix Brother HL-1110 printing blank page problem
+14.9k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+12.4k Golang : Set image canvas or background to transparent
+17.4k Golang : Set, Get and List environment variables