golang string to bytes
package main
import (
"fmt"
)
func main() {
str := "Hello, Golang!"
// Convert string to byte slice
bytes := []byte(str)
fmt.Printf("String: %s\n", str)
fmt.Printf("Bytes: %v\n", bytes)
}
Explanation:
- Import necessary packages:
fmt
for formatted I/O. - Define the
main
function. - Create a string variable
str
containing the text "Hello, Golang!". - Convert the string
str
to a byte slice using[]byte(str)
. This converts each character in the string to its corresponding byte representation. - Print the original string and the byte representation using
fmt.Printf
with format specifiers%s
for the string and%v
for the byte slice.