【发布时间】:2021-08-03 06:41:24
【问题描述】:
我的要求是将字节流转换为我的结构类型,它具有预定义的数据长度。 在下面的示例中,我可以将字节转换为“测试”对象并读取数据(func buffertoStruct 演示了这一点),
但问题是
我需要根据字符串或整数长度转换为数据类型。现在没有发生。
我有很多不同的结构,比如“类型测试”,每个结构都有大量的数据变量。所以根据大小将字节一一复制到struct Test变量中是行不通的。
我在想什么解决方案:
我正在考虑在数据结构中保留所有结构变量名称、大小、类型,并基于此循环切片字节流
type datadetails struct {
name string //ex: uniqnum, guid etc
size int //9 ,32
datatype string //int, string, etc int for uniqnum, string for guid
}
问题:需要比这更好的解决方案吗? 到目前为止,这是我的示例。
package main
import (
"bytes"
"encoding/gob"
"log"
"fmt"
)
type Test struct{
uniqnum int64 //9 char in byte stream ex: 708008123 (int)
guid string //exactly is 32 -chars
flag byte //string 1 char
printnum string //6 char
}
func convertintorec(data []byte) {
fmt.Println(data)
//convert byte data into Test record
}
func buffertoStruct(gbuffer []byte,pobj *Test ) {
tmp :=bytes.NewBuffer(gbuffer)
dec := gob.NewDecoder(tmp)
err := dec.Decode(pobj)
if err != nil {
log.Fatal("decode error:", err)
}
}
func main() {
bdata := []byte("9885455612guidstartshere12345678901234567F")
convertintorec(bdata)
}
【问题讨论】:
标签: go