-
智慧大石
使用strconv.ParseUint(文档)。var s = "05f8"var base = 16var size = 16value, err := strconv.ParseUint(s, base, size)value2 := uint16(value) // done!请注意,输出值是 an uint64,您必须在使用它之前将其转换为您键入的内容。注意 (bis) size 参数控制要转换为的 uint 的最大大小,因此溢出检查正确完成。
-
慕雪6442864
如果您有兴趣将 astring变成[]uint16,您可以执行以下操作:package mainimport ( "fmt" "golang.org/x/sys/windows")func main() { a, e := windows.UTF16FromString("05f8") if e != nil { panic(e) } fmt.Printf("%q\n", a) // ['0' '5' 'f' '8' '\x00']}或者,如果您确定不string包含 NUL 字节,则可以执行以下操作:package mainimport ( "fmt" "golang.org/x/sys/windows")func main() { a := windows.StringToUTF16("05f8") fmt.Printf("%q\n", a) // ['0' '5' 'f' '8' '\x00']}https://pkg.go.dev/golang.org/x/sys/windows#StringToUTF16https://pkg.go.dev/golang.org/x/sys/windows#UTF16FromString
-
POPMUISE
我绝不声称自己是 Go 开发人员,我欢迎对此提供反馈,但我试图将端口的 env 变量从字符串转换为 uint16。我能够让它与:文件: main.gopackage mainimport ( "log" "os" "strconv")var PORT = os.Getenv("PORT")func main() { portAsInt, err := strconv.ParseInt(PORT, 0, 16) if (err != nil) { log.Fatal(err) } // Use as needed with uint16() log.Println("Listening on port:", uint16(portAsInt))}运行应用程序:PORT=3000 go run main.go;# Expected Output:# Listening on port: 3000