首页 > 其他分享 >Go - Decoding Data with a Customized Binary Format to Structs

Go - Decoding Data with a Customized Binary Format to Structs

时间:2023-10-05 10:34:34浏览次数:44  
标签:binary err Binary buf Format Customized BigEndian file data

Problem: You want to decode the customized binary format back to structs.


Solution: Use the encoding/binary package to take data from the binary format and reconstruct structs from it.

 

func   main ()   { 
      var   data   Meter 
      file ,   err   :=   os . Open ( "bindata" ) 
      if   err   !=   nil   { 
          log . Println ( "Cannot  read  file:" ,   err ) 
      } 
      err   =   binary . Read ( file ,   binary . BigEndian ,   & data ) 
      if   err   !=   nil   { 
          log . Println ( "Cannot  read  binary:" ,   err ) 
      } 
}

Start with creating a struct to contain your data. Instead of Write you use Read , passing the reader to it, the byte order, and the struct instance you want to store data. This will read the bytes from the file and write them to the struct.

Here’s how you can do it manually, instead of using a one - liner like Read :

func   main ()   { 
      var   data   Meter   =   Meter {} 
      file ,   err   :=   os . Open ( "data.bin" ) 
      if   err   !=   nil   { 
          log . Println ( "Cannot  read  file:" ,   err ) 
      } 
      buf   :=   make ([] byte ,   24 ) 
      file . Read ( buf ) 
     defer   file . Close () 

      data . Id   =   binary . BigEndian . Uint32 ( buf [: 4 ]) 
      data . Voltage   =   math . Float32frombits ( binary . BigEndian . Uint32 ( buf [ 4 : 8 ])) 
      data . Current   =   math . Float32frombits ( binary . BigEndian . Uint32 ( buf [ 8 : 12 ])) 
      data . Energy   =   binary . BigEndian . Uint32 ( buf [ 12 : 16 ]) 
      data . Timestamp   =   binary . BigEndian . Uint64 ( buf [ 16 :]) 
      fmt . Println ( data ) 
}

As expected, the single function decoding takes longer than with gob, but the performance is fast when you manually decode the data into structs. It’s a bit more tedious to code, but the performance is there if you need it.

 

标签:binary,err,Binary,buf,Format,Customized,BigEndian,file,data
From: https://www.cnblogs.com/zhangzhihui/p/17743131.html

相关文章

  • Go - Encoding Data to a Customized Binary Format
    Problem: Youwanttoencodestructdatatoacustomizedbinaryformat.Solution: Designyourcustomizedformatandusetheencoding/binarypackagetowritedatainstructstoit. Usinggobhasacoupleofdrawbacks.First,gobissupportedbyGoonlya......
  • 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判断时,传入的参数跟匹配的值类型必须一致,于是调整了自己代......
  • 创建一个二叉排序树(Binary Search Tree)
    一、二叉排序树的定义左子树所有结点的值均小于根结点的值右子树所有结点的值均大于根节点的值左子树和右子树也是二叉排序树1.二叉排序树的结点结构typedefstructBSTNode{ /*二叉排序树的结点结构*/ intvalue; structBSTNode*left; structBSTNode*right;}BS......
  • Go - Creating Customized Errors
    Problem: Youwanttocreatecustomerrorstocommunicatemoreinformationabouttheerrorencountered.Solution: Createanewstring-basederrororimplementtheerrorinterfacebycreatingastructwithanErrormethodthatreturnsastring. Therea......
  • 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) ......