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
+9.5k Golang : Resolve domain name to IP4 and IP6 addresses.
+12.3k Golang : Linear algebra and matrix calculation example
+7.9k Golang : Sort lines of text example
+13.7k Golang : Rename directory
+11.5k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+10.2k Golang : Calculate Relative Strength Index(RSI) example
+7.3k Golang : Get final or effective URL with Request.URL example
+14.3k Golang : How to get Unix file descriptor for console and file
+14.1k nginx: [emerg] unknown directive "ssl"
+9.2k CodeIgniter : Load different view for mobile devices
+15.3k Golang : Get IP addresses of a domain name
+12.1k Golang : Convert IPv4 address to packed 32-bit binary format