How to use strconv.FormatUint() Function in Golang
Golang strconv.FormatUnit() function
The FormatUint() function is a strconv package built-in function that returns the string representation of an unsigned integer i in a given base, where the base can range from 2 to 36. For digit values greater than 10, the lower-case letters ‘a’ to ‘z’ are returned.
Syntax
func FormatUint(i uint64, base int) string
Parameters
i: An unsigned integer value that will be converted to a stringbase: is the base of the given value.
Return value
The strconv.FormatUint() function returns the string representation of i in a given base(2 <= base <= 36).
Code
The following code shows how to implement the strconv.FormatUint() function in Golang.
// Golang program to illustrate// strconv.FormatUint() Functionpackage mainimport ("fmt""strconv")func main() {// declaring variable y as unsigned integervar y uint64// declaring variable res as string typevar res string// assigning valuey = 28// Finds the string representation// of y value in the base 2// stores the result in variable resres = strconv.FormatUint(y, 2)// display resultfmt.Printf("\nVariable y is a Type %T", res)fmt.Printf("\nResult is %v\n", res)// reassigning valuey = 102// Finds the string representation// of y value in the base 16// stores the result in variable resres = strconv.FormatUint(y, 16)// display resultfmt.Printf("\nReassign value of y\n")fmt.Printf("\nVariable y is a Type %T", res)fmt.Printf("\nResult is %v", res)}
Code explanation
-
Line 4: Adding package main.
-
Lines 5 to 8: Importing necessary packages in Golang project.
-
Lines 11 - 21: Defining the
main()function, variableyof unsigned integer and assign a value to it, then passed the variable in thestrconv.FormatUint()function which finds the string representation ofyvalue in the base 2. The result is stored in variableres, which is finally displayed.