Majonsi
Majonsi

Reputation: 414

How do I convert a string value in uint16 in Go lang?

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!

Upvotes: 7

Views: 15173

Answers (3)

codingwithmanny
codingwithmanny

Reputation: 1184

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

Upvotes: 2

Zombo
Zombo

Reputation: 1

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']
}

Upvotes: 2

Elwinar
Elwinar

Reputation: 9509

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.

Upvotes: 16

Related Questions