I'm researching a solution in order to convert a string (in my case the string is "05f8") into a uint16.I made research but I don't find a solution.Does anyone know how to do this?
Thanks for your help!
In order to convert string to integer type in Golang, you can use the following methods. 1. Atoi() Function: The Atoi stands for ASCII to integer and returns the result of ParseInt(s, 10, 0) converted to type int.
You can convert numbers to strings by using the strconv. Itoa method from the strconv package in the Go standard libary. If you pass either a number or a variable into the parentheses of the method, that numeric value will be converted into a string value.
You can convert Golang “type []string” to string using string. Join() function, which takes two parameters. It returns a string.
Use strconv.ParseUint
(doc).
var s = "05f8"
var base = 16
var size = 16
value, err := strconv.ParseUint(s, base, size)
value2 := uint16(value) // done!
Note that the output value is an uint64
, you have to cast it to you type before using it.
Note (bis) that the size parameter control the maximum size of the uint to convert to, so the overflow check is done correctly.
If you are interested in turning a string
into []uint16
, you can do:
package main
import (
"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']
}
or, if you are certain string
contains no NUL bytes, you can do this:
package main
import (
"fmt"
"golang.org/x/sys/windows"
)
func main() {
a := windows.StringToUTF16("05f8")
fmt.Printf("%q\n", a) // ['0' '5' 'f' '8' '\x00']
}
By no means do I claim to be a go developer, and I welcome feedback on this, but I was trying to convert an env variable for a port from a string to uint16. I was able to get it working with:
File: main.go
package main
import (
"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))
}
Running application:
PORT=3000 go run main.go;
# Expected Output:
# Listening on port: 3000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With