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
+14.2k Golang : Delete certain files in a directory
+8.1k Golang : Timeout example
+5.3k Golang : Map within a map example
+8.9k Golang : Convert octal value to string to deal with leading zero problem
+20.5k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+8.3k Golang : Changing a RGBA image number of channels with OpenCV
+11.3k Golang : Covert map/slice/array to JSON or XML format
+17.6k Golang : Populate dropdown with html/template example
+4.9k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+6.4k Golang : Lock executable to a specific machine with unique hash of the machine
+5k Golang : Experimenting with the Rejang script