Home > Software design >  storing byte array into a string variable in Go lang
storing byte array into a string variable in Go lang

Time:09-16

I am using Go Lang for the first time. I have a byte array which I want to send over a socket. Currently, my socket data has string variables msg1,msg2, msg3. I want to append my byte array to it. Below is the code snippet.

var arr1 [4]byte = [4]byte{11,22,33,44}

addr := msg1   msg2   msg3
socket.Send(addr, 0)

But when I try to do that I get an error.

addr := msg1   msg2   msg3   string(arr1)

Error: cannot convert arr1 (type [4]byte) to type string

What should I do in this case?

Actual code

package main
import "fmt"

var arr1 [4]byte = [4]byte{11,22,33,44}
func main() {
    data := "msg1"   string(arr1[:])
  fmt.Printf("\n%s",data)
}

CodePudding user response:

A byte array cannot be converted to a string, but a byte slice can:

addr := msg1   msg2   msg3   string(arr1[:])

Or declare the arr1 as a byte slice:

var arr1 = []byte{11,22,33,44}

CodePudding user response:

byte is not string, read https://en.wikipedia.org/wiki/ASCII .

Guess u want this:

// var arr1 [4]byte = [4]byte{11, 22, 33, 44}
var arr1 [4]string = [4]string{"11", "22", "33", "44"}

func main() {
    data := "msg1"   arr1[0]   arr1[1]   arr1[2]   arr1[3]
    fmt.Printf("\n%s", data)
}

CodePudding user response:

Using the append(), I have given you two ways. I don't know which of the way you really want. But I hope one of these ways will be helpful for you.

package main

import "fmt"

var arr [4]string = [4]string{"11", "22", "33", "44"}
var messages [3]string = [3]string{"msg1", "msg2", "msg3"}

func main() {
    // fmt.Println(arr[0:4])

    // One way
    appending1 := append(messages[0:1], arr[0])
    appending2 := append(messages[1:2], arr[1])
    appending3 := append(messages[2:], arr[2])
    fmt.Println(appending1)
    fmt.Println(appending2)
    fmt.Println(appending3)

    // Second way
    appending1 := append(messages[0:1], arr[0], arr[1], arr[2], arr[3])
    appending2 := append(messages[1:2], arr[0], arr[1], arr[2], arr[3])
    appending3 := append(messages[2:3], arr[0], arr[1], arr[2], arr[3])
    fmt.Println(appending1)
    fmt.Println(appending2)
    fmt.Println(appending3)
}

One way result

[11 msg1]
[22 msg2]
[33 msg3]

Second way result

[msg1 11 22 33 44]
[msg2 11 22 33 44]
[msg3 11 22 33 44]

CodePudding user response:

package main

import (
    "encoding/hex"
    "fmt"
)

var byteArray [4]byte = [4]byte{11, 22, 33, 44}

func main() {
    msg1 := "HI"
    msg2 := "Hello"
    msg3 := "There"

    byteArrayToString := hex.EncodeToString(byteArray[:])
    fmt.Printf("\n%s", msg1 msg2 msg3 byteArrayToString)
}
  • Related