Golang convert integer to unicode character

前端 未结 2 1764
难免孤独
难免孤独 2021-01-28 21:29

Given the following input:

intVal := 2612
strVal := \"2612\"

What is a mechanism for mapping to the associated unicode value as a string.

相关标签:
2条回答
  • 2021-01-28 22:14

    2612 is not the integer value of the unicode rune, the integer value of \u2612 is 9746. The string "2612" is the hex value of the rune, so parse it as a hex number and convert it to a rune.

    i, err := strconv.ParseInt(strVal, 16, 32)
    if err != nil {
        log.Fatal(err)
    }
    r := rune(i)
    fmt.Println(string(r))
    

    https://play.golang.org/p/t_e6AfbKQq

    0 讨论(0)
  • 2021-01-28 22:23

    This one works:

    fmt.Println("\u2612")
    

    Because an interpreted string literal is specified in the source code, and the compiler will unquote (interpret) it. It is not the fmt package that processes this unquoting.

    This doesn't work:

    fmt.Println("\\u" + strVal)
    

    Because again an interpreted string literal is used which will be resolved to a string value \u, and then it will be concatenated with the value of the local variable strVal which is 2612, so the final string value will be \u2612. But this is not an interpreted string literal, this is the "final" result. This won't be processed / unquoted further.

    Alternatively to JimB's answer, you may also use strconv.Unquote() which does an unquoting similar to what the compiler does.

    See this example:

    // The original that works:
    s := "\u2612"
    fmt.Println(s, []byte(s))
    
    // Using strconv.Unquote():
    strVal := "2612"
    s2, err := strconv.Unquote(`"\u` + strVal + `"`)
    fmt.Println(s2, []byte(s2), err)
    fmt.Println(s == s2)
    

    Output (try it on the Go Playground):

    ☒ [226 152 146]
    ☒ [226 152 146] <nil>
    true
    

    Something to note here: We want to unquote the \u2612 text by strconv.Unquote(), but Unquote() requires that the string to be unquoted to be in quotes ("Unquote interprets s as a single-quoted, double-quoted, or backquoted Go string literal..."), that's why we pre- and postpended it with a quotation mark.

    0 讨论(0)
提交回复
热议问题