How to Convert Uint16 to String in Golang

To convert a uint16 value to a string in Go, you can use the “strconv.FormatUint()” or “strconv.Itoa()” function.

Method 1: Using the strconv.FormatUint() function

The strconv.FormatUint() function converts unsigned integer values (e.g., uint, uint16, uint32, uint64) to strings. The FormatUint() function takes two arguments: the unsigned integer value (as uint64) and the base (radix) of the number system to use for the string representation.

Example

package main

import (
  "fmt"
  "strconv"
)

func main() {
  var myUint16 uint16 = 42

  // Convert uint16 to string using strconv.FormatUint()
  myString := strconv.FormatUint(uint64(myUint16), 10)

  fmt.Println("Converted uint16 to string:", myString)
}

Output

Converted uint16 to string: 42

In this code, we converted a uint16 value to a string by casting the uint16 value to a uint64 using uint64(myUint16) and then passing the resulting uint64 value and the base (10, for decimal representation) to the strconv.FormatUint() function. The converted string is then printed to the console.

Method 2: Using the strconv.Itoa() function

The strconv.Itoa() function takes an int as an argument, and you need to convert your uint16 value to an int and then use the strconv.Itoa() function to convert an int to a string.

Example

package main

import (
  "fmt"
  "strconv"
)

func main() {
  var myUint16 uint16 = 42

  // Convert uint16 to int, then to string using strconv.Itoa()
  myString := strconv.Itoa(int(myUint16))

  fmt.Println("Converted uint16 to string:", myString)
}

Output

Converted uint16 to string: 42

In this code, we converted a uint16 value to a string by casting the uint16 value to an int using the int(myUint16) function, then passing the resulting int value to the strconv.Itoa() function. The converted string is then printed to the console.

Leave a Comment