读取二进制数据

中继器357

我正在尝试从二进制文件读取数据。一个数据块的长度为76个字节(随该块中间2个字节的“主要数据项”的数量而变化)。第一个数据为4字节,第二个数据为4字节,然后有一堆2字节的主要数据项,最后是2个2字节的数据。

在此处输入图片说明

基于此Delphi示例,我学习了如何使用以下代码读取文件:

short AShortInt; // 16 bits
int AInteger; // 32 bits
try
{
 infile=new TFileStream(myfile,fmOpenRead); // myfile is binary
 BR = new TBinaryReader(infile, TEncoding::Unicode, false);
 for (int rows = 0; rows < 5; rows++) {  // just read the first 5 blocks of data for testing
  AInteger = BR->ReadInt32(); // read first two 4 byte integers for this block
  AInteger = BR->ReadInt32();
  for (int i = 0; i < 32; i++) { // now read the 32 2-byte integers from this block
   AShortInt = BR->ReadInt16();
  }
  AShortInt = BR->ReadInt16(); // read next to last 2-byte int
  AShortInt = BR->ReadInt16(); // read the last 2-byte int
}
delete infile;
delete BR;
Close();
}
catch(...)
{
 delete infile;  // closes the file, doesn't delete it.
 delete BR;
 ShowMessage("Can't open file!");
 Close();
}

但是,我想做的是使用一个76字节宽的缓冲区读取整个块,然后从该缓冲区中选取各种数据。根据这个问题整理了以下代码,可以将整个数据块读入缓冲区。

UnicodeString myfile = System::Ioutils::TPath::Combine(System::Ioutils::TPath::GetDocumentsPath(), "binaryCOM.dat");
TFileStream*infile=0;
try
{
 infile=new TFileStream(myfile,fmOpenRead);
 const int bufsize=76;
 char*buf=new char[bufsize];
 int a = 0;
 while(int bytesread=infile->Read(buf,bufsize)) {
   a++; // just a place to break on Run to Cursor
 }
 delete[]buf;
}
catch(...)
{
  delete infile;  
  ShowMessage("Can't open file!");
  Close();
}

但是我无法弄清楚如何将子集中的字节子组合在一起。有没有办法串联 字节所以我可以将数据块读到76字节的缓冲区中,然后在下面做类似的事情?

unsigned int FirstDatum = buf[0]+buf[1]+buf[2]+buf[3];  // concatenate the 4 bytes for the first piece of data

这将是内置于C ++ Builder 10.3.2中的Win32,iOS和Android的FMX应用。

中继器357

这是我根据雷米(Remy)的建议修改的代码TMemoryStream

UnicodeString myfile = System::Ioutils::TPath::Combine(System::Ioutils::TPath::GetDocumentsPath(), "binaryCOM.dat");

TMemoryStream *MS=0;
TBinaryReader *BR=0;
std::vector<short> myArray;
short AShortInt;
int AInteger;
int NumDatums = 32; // the variable number of 2-byte main datums

try
{
  MS = new TMemoryStream();
  MS->LoadFromFile(myfile);
  BR = new TBinaryReader(MS, TEncoding::Unicode, false);
  for (int rows = 0; rows < 5; rows++) {  // testing with first 5 blocks of data
    AInteger = BR->ReadInt32(); // read first two 4 byte integers
    AInteger = BR->ReadInt32(); // here
    for (int i = 0; i < NumDatums; i++) {  // read the main 2-byte data
      AShortInt = BR->ReadInt16();
      myArray.push_back(AShortInt); // push it into vector
    }
    AShortInt = BR->ReadInt16(); // read next to last 2-byte int
    AShortInt = BR->ReadInt16(); // read the last 2-byte int
    // code here to do something with this block of data just read from file
  }
}
delete MS;
delete BR;
}
catch(...)
{
 delete MS;  
 delete BR;
 ShowMessage("Can't open file.");
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章