Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte endian convert by using encoding/binary in Go

Tags:

go

I got the runtime error message Write T1 binary.Read: invalid type main.T1

package main

import (
    "encoding/binary"
    "net"
)

type T1 struct {
    f1 [5]byte
    f2 int
}

func main() {
    conn, _ := net.Dial("tcp", ":12345")
    l1 := T1{[5]byte{'a', 'b', 'c', 'd', 'e'}, 1234}
    binary.Write(conn, binary.BigEndian, &l1)
}

I wish to use the endian auto convert function, how could I do? By the way, is there more efficient way?

like image 836
Daniel YC Lin Avatar asked Nov 07 '11 16:11

Daniel YC Lin


People also ask

What is Golang binary?

Go Binaries is an open-source server allowing non-Go users to quickly install tools written in Golang, without installing the Go compiler or a package manager — all you need is curl . Let's take a look at how it works, and how to use it!

What is meant by binary encoding?

Binary encoding uses the binary digit, or bit, as the fundamental unit of information, and a bit may only be a '0' or a '1' (only two possibilities since it is a binary-encoded system). By combining bits, numbers larger than 0 or 1 may be represented, and these bit collections are called words.

What is byte in Golang?

The byte type in Golang is an alias for the unsigned integer 8 type ( uint8 ). The byte type is only used to semantically distinguish between an unsigned integer 8 and a byte. The range of a byte is 0 to 255 (same as uint8 ).


1 Answers

Use exported fixed size fields. For example,

package main

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

type T struct {
    F1 [5]byte
    F2 int32
}

func main() {
    var t1, t2 T
    t1 = T{[5]byte{'a', 'b', 'c', 'd', 'e'}, 1234}
    fmt.Println("t1:", t1)
    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.BigEndian, &t1)
    if err != nil {
        fmt.Println(err)
    }
    err = binary.Read(buf, binary.BigEndian, &t2)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("t2:", t2)
}

Output:

t1: {[97 98 99 100 101] 1234}
t2: {[97 98 99 100 101] 1234}
like image 148
peterSO Avatar answered Sep 26 '22 11:09

peterSO