In the Go language, a character is essentially a Unicode code point. The byte is the smallest unit of computer memory, which consists of 8 binary bits. In actual programming, characters need to be converted into bytes for processing, so that more flexible and efficient operations can be performed. This article will introduce several methods of converting characters to byte in golang.
Convert characters to bytes through type conversion
In golang, the character type rune is the type that represents Unicode code points. We can convert rune type characters into byte type byte through type conversion. The example is as follows:
package main import "fmt" func main() { s := "hello world" for _, c := range s { fmt.Printf("%d ", byte(c)) } }
In this example, the running result is:
104 101 108 108 111 32 119 111 114 108 100
Convert a string to a byte array through slicing
You can also use slicing to convert a string is a byte array. The sample code is as follows:
package main import "fmt" func main() { s := "hello world" b := []byte(s) for _, c := range b { fmt.Printf("%d ", c) } }
In this example, the running result is the same as the previous example.
Convert numeric strings to numeric types through strconv
In actual development, we often encounter situations where we need to convert numeric strings to numeric types. In golang, you can use the strconv package to perform this conversion operation. The sample code is as follows:
package main import ( "fmt" "strconv" ) func main() { str := "100" num, err := strconv.Atoi(str) if err != nil { panic(err) } fmt.Printf("num=%d ", num) }
In this example, the strconv.Atoi() function converts the string "100" to the numeric type num=100. If the conversion fails, an error message is returned.
Summary
This article introduces several methods of converting characters to byte in golang, including type conversion, slicing and the use of strconv package. In actual development, the most suitable conversion method needs to be selected according to specific scenarios. Hope this article is helpful to you.
The above is the detailed content of golang character to byte. For more information, please follow other related articles on the PHP Chinese website!