stringgoutf-8unicode-literalsrune

How to convert a utf8 literal (ie '\u1F606') to a rune? (NOT GET THE UTF8 FROM THE RUNE!)


I'm trying to generate sequential characters using the utf8 hex codes. For example first part, I'm terming "base" code : 259 second part, Im' terming "end" code : 1 (or, 2, or A, or F, etc)

These are coming in as strings. Once I append the end code and get a complete string (ie: 259E), how can I convert that into the actual utf8 representation (or "character")

I'm not sure where to start. I know that string(rune('\u259E') will give me the representation ( ▞), but I don't know how to get the string into the rune cast as a (single-quoted) utf8 character code.

package main

import "fmt"

func main() {
    s1 := "259"
    s2 := "E"
    s3 := "\\u"+s1+s2
    fmt.Println(s3)
    fmt.Println(string(rune('\u259E'))) 
}

The desired outcome is that I'm able to return a utf8 character (and potentially surrogate pairs) from generated string representations of the codes.

The overall gist (for example) is that I'd like the string value "272A" to return as : ✪


Solution

  • Parse the hex value into an int32.

    Then cast that value to a rune in the println.

    package main
    
    import "fmt"
    import "strconv"
    
    func main() {
        s1 := "259"
        s2 := "E"
        s3, err := strconv.ParseInt(s1+s2, 16, 32)
        fmt.Println(string(rune(s3)))
        fmt.Println(err)
    }