In Go, how can I convert a struct to a byte array?

Related searches

I have an instance of a struct that I defined and I would like to convert it to an array of bytes. I tried []byte(my_struct), but that did not work. Also, I was pointed to the binary package, but I am not sure which function I should use and how I should use it. An example would be greatly appreciated.

I assume you want something like the way C handles this. There is no built in way to do that. You will have to define your own serialization and deserialization to and from bytes for your struct. The binary package will help you encode the fields in your struct to bytes that you can add to the byte array but you will be responsible for specifying the lengths and offsets in the byte array that will hold the fields from your struct.

Your other options are to use one of the encoding packages: http://golang.org/pkg/encoding/ such as gob or json.

EDIT:

Since you want this for making a hash as you say in your comment the easisest thing to do is use []byte(fmt.Sprintf("%v", struct)) like so: http://play.golang.org/p/yY8mSdZ_kf

golang convert a struct to a byte array, I have an instance of a struct that I defined and I would like to convert it to an array of bytes. I tried []byte(my_struct), but that did not work. Also, I was pointed to � > the method Set and the param is a array byte > > func (db *DB) Set(key, value []byte) (err error) { > > } > and i would like to convert one structure to array byte.. Given the data store, I assume your program is the only consumer of the encoded values. In that case encoding/gob should work fine for you. Here's a usage example.

One possible solution is the "encoding/gob" standard package. The gob package creates an encoder/decoder that can encode any struct into an array of bytes and then decode that array back into a struct. There's a great post, here.

As others have pointed out, it's necessary to use a package like this because structs, by their nature, have unknown sizes and cannot be converted into arrays of bytes.

I've included some code and a play.

package main

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "log"
)

type P struct {
    X, Y, Z int
    Name    string
}

type Q struct {
    X, Y *int32
    Name string
}

func main() {
    // Initialize the encoder and decoder.  Normally enc and dec would be
    // bound to network connections and the encoder and decoder would
    // run in different processes.
    var network bytes.Buffer        // Stand-in for a network connection
    enc := gob.NewEncoder(&network) // Will write to network.
    dec := gob.NewDecoder(&network) // Will read from network.
    // Encode (send) the value.
    err := enc.Encode(P{3, 4, 5, "Pythagoras"})
    if err != nil {
        log.Fatal("encode error:", err)
    }

    // HERE ARE YOUR BYTES!!!!
    fmt.Println(network.Bytes())

    // Decode (receive) the value.
    var q Q
    err = dec.Decode(&q)
    if err != nil {
        log.Fatal("decode error:", err)
    }
    fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y)
}

In Go, how can I convert a struct to a byte array? - arrays - php, We then convert it to a byte slice with a conversion. Bytes. Unmarshal: We invoke Unmarshal by passing a pointer to an empty array of structs. The Languages� And I figured since the SPI protocol sends one byte at a time, the best way to send my data would be to first convert the struct into a byte array (of the same size as my struct). Here is what I've got thus far:

I know this thread is old, but none of the answers were accepted, and there's a pretty simple way to do this.

https://play.golang.org/p/TedsY455EBD

important code from playground

import (
  "bytes"
  "fmt"
  "encoding/json"
)

type MyStruct struct {
  Name string `json:"name"`
}

testStruct := MyStruct{"hello world"}
reqBodyBytes := new(bytes.Buffer)
json.NewEncoder(reqBodyBytes).Encode(testStruct)

reqBodyBytes.Bytes() // this is the []byte

Golang JSON Example: Marshal, Unmarshal, How to convert C# Struct to Byte Array. Rate this: Please Sign up or sign in to vote. See more: C#. convert. marshalling. struct, + Hi, I have structure : struct

You should use a bytes buffer instead of a string, the other suggested methods create a SHA1 of variable length, the SHA1 standard length must be 20 bytes (160 bits)

package main

import (
    "crypto/sha1"
    "fmt"
    "encoding/binary"
    "bytes"
)

type myStruct struct {
    ID   string
    Data string
}

func main() {
    var bin_buf bytes.Buffer
    x := myStruct{"1", "Hello"}
    binary.Write(&bin_buf, binary.BigEndian, x)
    fmt.Printf("% x", sha1.Sum(bin_buf.Bytes()))
}

Try it yourself: http://play.golang.org/p/8YuM6VIlLV

It's a really easy method and it works great.

possible duplicates: how convert struct char array in c portable way of writing c struct file (serialisation c) i looking converting structure byte array in c , confused in doing that.please show me right way in achieving that. in advance.

Serialization is likely proper answer.

But if you consent to unsafety and actually need to read struct as bytes, then relying on byte array memory representation might be a bit better than relying on byte slice internal structure.

type Struct struct {
    Src int32
    Dst int32
    SrcPort uint16
    DstPort uint16
}

const sz = int(unsafe.SizeOf(Struct{}))
var asByteSlice []byte = (*(*[sz]byte)(unsafe.Pointer(&struct_value)))[:]

Works and provides read-write view into struct, zero-copy. Two "unsafe" should hint enough that it may break badly.

How do I convert a structure that contains an array to a byte array in C#? There was a question here about a struct without array. But if the struct contains an array like this: public struct Di

takes the address of struct_data and increases it by i times the size of the structure. Try this instead: *((char *) &struct_data + i) This converts the address of struct_data to a char * and then adds the index, and then uses the dereference operator (unary *) to get the "char" at that address.

See Convert between rune array/slice and string. Convert string to bytes. When you convert a string to a byte slice, you get a new slice that contains the same bytes as the string. b := []byte("ABC€") fmt.Println(b) // [65 66 67 226 130 172] Note that the character € is encoded in UTF-8 using 3 bytes. See the Go rune article for more on UTF

In Golang, to convert a string to byte array, you get a slice that contains the bytes of the string. In Go, a string is, in effect, a read-only slice of bytes. It’s essential to state right up front that a string holds arbitrary bytes. It is not required to hold Unicode text, UTF-8 text, or any other predefined format.

Comments
  • Thank you for your quick answer. The reason I'm trying to do this is to be able to get a hash (I'm trying to use SHA-256, but it could be another) of my struct. Do you know of an easier way of doing this?
  • I've edited the answer to show an easy way to do what you want.
  • Thanks again. I tried doing that, but I got the following error message: "multiple-value fmt.Printf() in single-value context". Do you know why that is happening?
  • @abw333, it is because usage of Printf seems to be a typo. You should use Sprintf, as is demonstrated by the code behind the link in Jeremy's answer.
  • yeah sorry about that. It was a typo.
  • This will convert the struct to a bytes array in "JSON" format. I'm assuming the question is about converting the struct to a bytes array in "Binary" format (For lower memory/disk consumption).
  • Indeed it will return an array of [123 34 110 97 109 101 34 58 34 104 101 108 108 111 32 119 111 114 108 100 34 125 10] or {"name":"hello world"}LF
  • Link-only answers are deprecated.
  • Thank you Der, I'll edit this. Was my first comment.
  • Doesn't look like this works because myStruct isn't fixed size. play.golang.org/p/IGA_lgRVNX
  • Did it work? Check the err returned from binary.Write reveals "binary.Write: invalid type main.myStruct"....
  • Proof that this does not work. Would've been a great thing though.. play.golang.org/p/gpBUXMnaOUJ
  • Exactly, I only scrolled down looking if someone had given this answer. The rest of the answers are way too over convoluted for such a simple problem. Good job!
  • @chewbapoclypse this only works with structs with no internal pointers. Tt won't work with strings, since string has an internal pointer to an underlying sequence of elements. You have to keep your string data in arrays for this to work.