Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

parsing

hex

go

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!

like image 686
Majonsi Avatar asked Mar 02 '16 17:03

Majonsi


People also ask

How to convert string to number in Golang?

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.

How do you convert something to string in go?

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.

How to convert[] string to string in Go?

You can convert Golang “type []string” to string using string. Join() function, which takes two parameters. It returns a string.


3 Answers

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.

like image 167
Elwinar Avatar answered Oct 16 '22 12:10

Elwinar


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']
}
  • https://pkg.go.dev/golang.org/x/sys/windows#StringToUTF16
  • https://pkg.go.dev/golang.org/x/sys/windows#UTF16FromString
like image 28
Zombo Avatar answered Oct 16 '22 13:10

Zombo


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
like image 2
codingwithmanny Avatar answered Oct 16 '22 12:10

codingwithmanny