How to convert uint8 to string

后端 未结 5 1199
感动是毒
感动是毒 2020-11-27 08:10

http://play.golang.org/p/BoZkHC8_uA

I want to convert uint8 to string but can\'t figure out how.

  package main

  import \"fmt\"
  import \"strconv\         


        
相关标签:
5条回答
  • 2020-11-27 08:19

    There is a difference between converting it or casting it, consider:

    var s uint8 = 10
    fmt.Print(string(s))
    fmt.Print(strconv.Itoa(int(s)))
    

    The string cast prints '\n' (newline), the string conversion prints "10". The difference becomes clear once you regard the []byte conversion of both variants:

    []byte(string(s)) == [10] // the single character represented by 10
    []byte(strconv.Itoa(int(s))) == [49, 48] // character encoding for '1' and '0'
    
    see this code in play.golang.org
    0 讨论(0)
  • 2020-11-27 08:29

    You can do it even simpler by using casting, this worked for me:

    var c uint8
    c = 't'
    fmt.Printf(string(c))
    
    0 讨论(0)
  • 2020-11-27 08:29

    There are no automatic conversions of basic types in Go expressions. See https://talks.golang.org/2012/goforc.slide#18. A byte (an alias of uint8) or []byte ([]uint8) has to be set to a bool, number or string.

    package main
    
    import (
        . "fmt"
    )
    
    func main() {
        b := []byte{'G', 'o'}
        c := []interface{}{b[0], float64(b[0]), int(b[0]), rune(b[0]), string(b[0]), Sprintf("%s", b), b[0] != 0}
        checkType(c)
    }
    
    func checkType(s []interface{}) {
        for k, _ := range s {
            // uint8 71, float64 71, int 71, int32 71, string G, string Go, bool true
            Printf("%T %v\n", s[k], s[k])
        }
    }
    

    Sprintf("%s", b) can be used to convert []byte{'G', 'o' } to the string "Go". You can convert any int type to a string with Sprintf. See https://stackoverflow.com/a/41074199/12817546.

    But Sprintf uses reflection. See the comment in https://stackoverflow.com/a/22626531/12817546. Using Itoa (Integer to ASCII) is faster. See @DenysSéguret and https://stackoverflow.com/a/38077508/12817546. Quotes edited.

    0 讨论(0)
  • 2020-11-27 08:39

    use %c

        str := "Hello"
        fmt.Println(str[1]) // 101
        fmt.Printf("%c\n", str[1])
    
    0 讨论(0)
  • 2020-11-27 08:40

    Simply convert it :

        fmt.Println(strconv.Itoa(int(str[1])))
    
    0 讨论(0)
提交回复
热议问题