Golang : convert rune to unicode hexadecimal value and back to rune character
There are times when we need to convert a rune to unicode hexadecimal style for storage purpose, encryption, manipulation and etc. Below is a short example on how to convert a rune to unicode hexadecimal value and how to convert unicode hexadecimal value back to rune character.
package main
import (
"fmt"
"strconv"
)
func main() {
// translate character to rune
r := rune('黄')
// extra the unicode \uxxxx value
unicode := strconv.QuoteRuneToASCII(r)
fmt.Println(string(r) + " unicode hex value is : ", unicode)
// convert back unicode to rune
// this WILL NOT work, it just prints out the unicode string
fmt.Println("\"\\u" + unicode[3:len(unicode)-1] + "\"")
// strangely, this will work
fmt.Println("\u9ec4")
// therefore, to convert a unicode back to rune
// use strconv.Unquote
char, _ := strconv.Unquote(unicode)
fmt.Println(unicode + " rune character is : ", char)
}
Output :
黄 unicode hex value is : '\u9ec4'
"\u9ec4"
黄
'\u9ec4' rune character is : 黄
Hope you may find this short tutorial useful in dealing with unicode and rune.
Reference :
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.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+10.7k Golang : Split strings into command line arguments
+11k Android Studio : Highlight ImageButton when pressed on example
+12.8k How to automatically restart your crashed Golang server
+7.9k Golang : HTTP Routing with Goji example
+6.1k Golang : Validate credit card example
+4.9k Golang : Launching your executable inside a console under Linux
+4.4k Javascript : How to loop over and parse JSON data?
+7.6k Linux/Unix : fatal: the Postfix mail system is already running
+6.9k Golang : Gomobile init produce "iphoneos" cannot be located error
+3.6k Javascript : Access JSON data example
+13.1k Golang : ROT47 (Caesar cipher by 47 characters) example