Golang string to uint8 type casting [SOLVED]


GOLANG Solutions, GO

Different methods for golang string to uint8 type casting

Golang (The Go programming language) is one of the most elegant and pleasant languages to work with, and in any programming language, you often encounter type casting, for different purposes, one example, is when you get a Json response from an API, and you have some numbers that has to be converted to a numeric types (floats, integers, unsigned integers etc) or the opposite from a number, a integer or float etc. to a string.  We already covered the Golang Type Casting in detail in our of our previous articles, but in this tutorial we will only concentrate on golang string to uint8 type casting with example.

Functions we will explore in this article:

  • strconv.Atoi
  • fmt.Sscan
  • strconv.ParseInt
  • string()
  • strconv.Itoa
  • strconv.FormatInt

 

NOTE:
We will be using different kinds of formatting verbs throughout this tutorial such as %d, %T, %v, %s. If you are not familiar with these verbs then I would strongly recommend to first go through Different formatting functions in GO

 

Type cast string to uint8

Method-1: Strconv.Atoi

On the other hand, when you have to convert a string, say a price or any other numeric value, to an actual integer, we use the strconv package strconv.Atoi(...) like so

func main() {
	s := "111"
	fmt.Printf("%v %T\n", s, s) //111 string
	valInt, _ := strconv.Atoi(s)
	fmt.Printf("%v %T\n", valInt, valInt) // 111 int
}

To print out

111 string
111 int

Be careful here, you might pass in a value, Golang wont know how to print to cast, so you run to, like using 111a the valInt will get the value 0 int

func main() {
	s := "111a"
	fmt.Printf("%v %T\n", s, s) //111a string
	in, err := strconv.Atoi(s)
	if err != nil {
		fmt.Println(err) //strconv.Atoi: parsing "111a": invalid syntax
	}
	fmt.Printf("%v %T\n", in, in) // 0 int
}
111a string
strconv.Atoi: parsing "111a": invalid syntax
0 int

So you have to check for errors to make sure its the correct value you need.
This is what you need for converting from string to integer like if you read balance or price from Stripe API, or others.

 

Method-2: Strconv.ParseInt

If you look for greater flexibly, Golang offers the ParseInt method which has a function signature accepting both, base and bitsize.

ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.

To use it equivalently to strconv.Atoi We would

package main

import (
	"fmt"
	"strconv"
)

func main() {

	s := "111"
	fmt.Printf("%v %T\n", s, s) // 111 string
	in, err := strconv.Atoi(s)
	if err != nil {
		fmt.Println(err) // 
	}
	fmt.Printf("%v %T\n", in, in)//111 int

	flex, _ := strconv.ParseInt(s, 10, 0)
	fmt.Printf("%v %T\n", flex, flex) //111 int64
}

To print out

111 string
111 int
111 int64

If you are looking for a granular control of the type conversion, this is the function you need.

 

Method-3: fmt.Sscan

Finally if you want to convert a sequence. this description from the documentation explains it.

Sscan scans the argument string, storing successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.

So this tools accepts and scan the input string and then returns the scanned elements as integers. Here is the syntax of fmt.Sscan

func Sscan(str string, a ...any) (n int, err error)

You can check this simple example where we are converting string to integer:

package main

import (
	"flag"
	"fmt"
)

func main() {

	flag.Parse()
	s := flag.Arg(0)
	fmt.Printf("Original type: %T\n", s)

	var i int
	if _, err := fmt.Sscan(s, &i); err == nil {
		fmt.Printf("i=%d, type: %T\n", i, i)
	}
}

Output:

$ go run main.go 100
Original type: string
i=100, type: int

 

Type casting int to string

In golang there is two main ways to convert an int to a string, they look similar, but the difference is fundamental.

  • Using string()
  • Or using the strconv package like strconv.FormatInt() or strconv.Itoa

 

Method-1: Using String()

The string function, simply converts an integer value to a unicode code point. so a single character.

package main

import (
	"fmt"
)

func main() {
	// lets declare an integer of value 90
	var num int = 90

	// Print original type
	fmt.Printf("Original type: %T\n", num)

	// lets use string() function with 90 as the argument
	s1 := string(num)

	// print out the value, and the type
	fmt.Printf("New value: %s\n", s1)
	fmt.Printf("New Type: %T\n", s1)
}

This would print out

Z string

So Golang is printing out, the int as a UTF8 character, which 90, is equivalent to Z, in this case.  To demonstrate further, lets go from int to a string, then back to an int

func main() {
	// lets declare the int8 of value 90, and print it to demonstrate value and type
	var num int8 = 90
	fmt.Printf("%v %T\\n", num, num) // 	90 int8

	// lets convert using the string function, with num of value 90 as the argument
	s1 := string(num)
	fmt.Printf("%v %T\\n", s1, s1) // Z string

	// lets convert string of value Z, to an array of bytes, then print it out
	ab := []byte("Z")
	for _, v := range ab {
		fmt.Printf("%v %T\\n", v, v) // 90 uint8
	}
}

This prints out

90 int8
Z string
90 uint8

So the string() function returns a string of course, however it dose return the ASCII representation of a string.

This is what you need, when you want to convert from a bit to a string.

 

Strconv.Itoa or Strconv.FormatInt

On the other hand, To convert the same number you read, from int to string.

func main() {
	// Lets declare an integer num of value 91
	var num int = 91
	fmt.Printf("%v %T\n", num, num) // 91 int

	// lets convert 91 integer, to string using Itoa
	str := strconv.Itoa(num)
	fmt.Printf("%v %T\n", str, str) // 91 string

	// lets convert 91 integer, to string using FormatInt
	str2 := strconv.FormatInt(int64(num), 10)
	fmt.Printf("%v %T\n", str2, str2) // 91 string
}

This prints out

91 int
91 string
91 string

Now with this functions from the strconv package, we get the exact same output, but in a different type.

This is what you need when you want to show it to the user or print it somewhere.

So be careful which you need, the first is to decode to a string, the second is to print the exact letters to a string.


 

Conclusion

We learned how to convert string to uint8 and vice versa using different methods, Golang offers all the means, you just have to choose the right function for your need. happy coding.

 

Deepak Prasad

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment