首页 > 其他分享 >Go - Encoding Data to a Customized Binary Format

Go - Encoding Data to a Customized Binary Format

时间:2023-10-05 10:22:35浏览次数:32  
标签:binary Format err Binary buf Encoding file data struct

Problem: You want to encode struct data to a customized binary format.


Solution: Design your customized format and use the encoding/binary package to write data in structs to it.

 

Using gob has a couple of drawbacks. First, gob is supported by Go only and works best if both sender and receiver are written in Go. Second, gob stores the whole struct, labels and all, which makes the encoded binary data relatively large. In fact, there is no difference between the size of a piece of JSON data compared to the size of a piece of gob data when they have the same content!
An alternative is to strip away the labels; for example, the Meter struct can be stored this way. Figure 10 - 1 shows how data for the Meter struct will be stored.

Remember uint8 is 1 byte, uint16 is 2 bytes, uint32 is 4 bytes, and uint64 is 8 bytes. You don’t need the labels if you know the positions of the values.

Writing this format is surprisingly easy. You simply use binary.Write to write the data from the struct instance into this format:

func   main ()   { 
      file ,   err   :=   os . Create ( "data.bin" ) 
      if   err   !=   nil   { 
          log . Println ( "Cannot  create  file:" ,   err ) 
      } 
      err   =   binary . Write ( file ,   binary . BigEndian ,   reading )
     if   err   !=   nil   { 
          log . Println ( "Cannot  write  to  file:" ,   err ) 
      } 
}

The first parameter is the writer you want to write to; in this case, it’s a file. The second parameter is the byte order for format. The encoding/binary supports both big - endian and little - endian, and in this case, you are using big - endian. The last parameter is the struct instance you’re taking the data from.

If you look at the file that’s created, it’s just 24 bytes, as opposed to the earlier gob format, which turned out to be 110 bytes. That’s a significant reduction if you’re moving smaller packets of data over a low - bandwidth network.

 

You might have thought it would encode faster but it’s only slightly better than encoding in JSON, and gob encoding beats it by quite a bit. In addition, it takes up more memory doing the job.

 

While binary.Write is the easiest way to encode customized binary data, you can also use the encoding/binary package to encode a struct instance manually. Here’s how this can be done:

func   main ()   { 
      file ,   err   :=   os . Create ( "data.bin" ) 
      if   err   !=   nil   { 
          log . Println ( "Cannot  create  file:" ,   err ) 
      } 
      defer   file . Close () 

      buf   :=   make ([] byte ,   24 ) 
      binary . BigEndian . PutUint32 ( buf [ 0 :],   reading . Id ) 
      binary . BigEndian . PutUint32 ( buf [ 4 :],   math . Float32bits ( reading . Voltage )) 
      binary . BigEndian . PutUint32 ( buf [ 8 :],   math . Float32bits ( reading . Current )) 
      binary . BigEndian . PutUint32 ( buf [ 12 :],   reading . Energy ) 
      binary . BigEndian . PutUint64 ( buf [ 16 :],   reading . Timestamp ) 
      file . Write ( buf ) 
}

It seems like a lot of work, and the file size remains the same, so check out the performance:

It’s a world of difference! The performance is significantly better, and it uses less memory than the Write alone.

 

标签:binary,Format,err,Binary,buf,Encoding,file,data,struct
From: https://www.cnblogs.com/zhangzhihui/p/17743122.html

相关文章

  • Go - Decoding gob Format Data to Structs
    Problem: Youwanttodecodegobformatdatabacktostructs.Solution: Usetheencoding/gobpackagetodecodethegobformatdatabacktostructs. funcread(datainterface{},filenamestring){file,err:=os.Open(&quo......
  • Go - Encoding Data to gob Format Data
    Problem: Youwanttoencodestructsintobinarygobformat.Solution: Usetheencoding/gobpackagetoencodethestructsintobytesthatcanbestoredorsentelsewhere. Theencoding/gobpackageisaGolibrarytoencodeanddecodeabinaryformat.The......
  • 【刷题笔记】67. Add Binary
    题目Giventwobinarystrings,returntheirsum(alsoabinarystring).Theinputstringsareboth non-empty andcontainsonlycharacters 1 or 0.Example1:Input:a="11",b="1"Output:"100"Example2:Input:a="10......
  • mybatis出现错误 java lang NumberFormatException:For input string:A1
    使用mybatis,当使用map传参并且在iftest判断时使用map中所传的参数时,可能会产生如题的报错,具体报错信息见下图:分析这个错误,自己调试也找过度娘,“坚信”自己代码并没问题,但是问题始终无法解决。最后在一个帖子看到说iftest判断时,传入的参数跟匹配的值类型必须一致,于是调整了自己代......
  • ​​pandas.get_dummies()​​ 是一个用于执行独热编码(One-Hot Encoding)的 pandas 函
    pandas.get_dummies()是一个用于执行独热编码(One-HotEncoding)的pandas函数。它用于将分类(或离散)特征转换为模型可以处理的二进制格式,以便更好地在机器学习算法中使用。独热编码将每个不同的类别值转换为一个新的二进制特征列,其中每个列代表一个类别,并且只有一个值为1,其余为0......
  • 创建一个二叉排序树(Binary Search Tree)
    一、二叉排序树的定义左子树所有结点的值均小于根结点的值右子树所有结点的值均大于根节点的值左子树和右子树也是二叉排序树1.二叉排序树的结点结构typedefstructBSTNode{ /*二叉排序树的结点结构*/ intvalue; structBSTNode*left; structBSTNode*right;}BS......
  • Common Certificate Formats
    为什么会有那么多种类的证书?一般而言,不同后缀的证书代表不同的编码、解码规则。要么是不同功能场景,要么是同一个功能只是不同厂商的不同风格罢了。不一一记录了,用到在查吧。Reference数字证书常见格式整理https://blog.csdn.net/zhulianhai0927/article/details/106452521......
  • java.net.ConnectException: Connection refused: no further information
    java.net.ConnectException:Connectionrefused:nofurtherinformation atsun.nio.ch.SocketChannelImpl.checkConnect(NativeMethod)~[na:1.8.0_91] atsun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)~[na:1.8.0_91] atio.netty.channe......
  • Social Infrastructure Information Systems Division, Hitachi Programming Contest
    A-HitachiString满足条件的串即为串长为偶数且相邻两个均为为hi,直接判断即可。代码:#include<iostream>#include<cstdio>#include<cstring>usingnamespacestd;constintN=15;intn;chars[N];intmain(){ scanf("%s",s+1); n=strlen(s+1); if(n&1) ......
  • SQL注入 --【过滤or(包含information、orderby这种也寄了)和and的类型】
    来自:[SWPU2019]Web1详见博客:https://blog.csdn.net/plant1234/article/details/124205120payload如下:查看行数1'/**/group/**/by/**/1,'1......直到1'/**/group/**/by/**/23,'1报错也就是说有22行找出回显点//找出回显点-1'/**/union/**/select/**/1,2,3,4,5,6,7......