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
+10.7k Golang : Get UDP client IP address and differentiate clients by port number
+17.1k Golang : How to tell if a file is compressed either gzip or zip ?
+10k Golang : Use regular expression to get all upper case or lower case characters example
+5.4k PHP : Fix Call to undefined function curl_init() error
+12.8k Golang : Get terminal width and height example
+4.3k Linux/MacOSX : Search and delete files by extension
+28k Golang : Connect to database (MySQL/MariaDB) server
+18.4k Golang : Send email with attachment
+29.1k Golang : Saving(serializing) and reading file with GOB
+10.6k Android Studio : Checkbox for user to select options example
+13.4k Golang : Set image canvas or background to transparent
+12.6k Swift : Convert (cast) Int or int32 value to CGFloat