如何将uint8转换为字符串

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

我想把uint8转换成字符串,但不知道怎么转换。

  package main

  import "fmt"
  import "strconv"

  func main() {

    str := "Hello"
    fmt.Println(str[1])  // 101

    fmt.Println(strconv.Itoa(str[1]))
  }

这给了我 prog.go:11: cannot use str[1] (type uint8) as type int in function argument [process exited with non-zero status]

有其他任何想法吗?

Simply convert it :

    fmt.Println(strconv.Itoa(int(str[1])))

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

var c uint8
c = 't'
fmt.Printf(string(c))

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 ' ' (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

This will do the job.

package main

import (
  "crypto/sha1"
  "encoding/hex"
  "fmt"
)

func main() {
  h := sha1.New()
  h.Write([]byte("content"))
  sha := h.Sum(nil)  // "sha" is uint8 type, encoded in base16

  shaStr := hex.EncodeToString(sha)  // String representation

  fmt.Printf("%x
", sha)
  fmt.Println(shaStr)
}