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
+23.3k Golang : Randomly pick an item from a slice/array example
+5.4k JavaScript/JQuery : Redirect page examples
+7.7k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+9.1k Golang : Populate or initialize struct with values example
+29.6k Golang : JQuery AJAX post data to server and send data back to client example
+5.5k Golang : Pad file extension automagically
+11.5k Golang : How to use if, eq and print properly in html template
+6.7k Elasticsearch : Shutdown a local node
+10.1k Golang : ffmpeg with os/exec.Command() returns non-zero status
+17.5k Golang : Find file size(disk usage) with filepath.Walk
+7k Get Facebook friends working in same company
+29.6k Golang : Save map/struct to JSON or XML file