读取二进制文件到txt,包括大小端转换

不多说,直接上代码

#include
#include
#include
#include
#include
#include
using namespace std;
#define L  101       
#define M  102    
#define N  103


void OnChange(float InParam, float &OutParam)
{
union
{
char ch[4];
float iTemp;
}u,r;
u.iTemp = InParam;
r.ch[0] = u.ch[3];
r.ch[1] = u.ch[2];
r.ch[2] = u.ch[1];
r.ch[3] = u.ch[0];
OutParam = r.iTemp;
}
int main()
{
   ofstream outfile("faultLabel.txt");
   FILE *fp;
   fp=fopen("faultLabel.dat","rb");
   float ***v;
   v=(float***)malloc(N*sizeof(float**));


   for (int i=0;i  v[i]=(float**)malloc(M*sizeof(float*));//分配空间,每个二级指针又指向m个一级指针
  for (int ii=0;ii  v[i][ii]=(float*)malloc(L*sizeof(float));//分配空间,每个一级指针指向长度为l的一维数组
  for ( int iii=0;iii  v[i][ii][iii]=0;
  fread(&v[i][ii][iii],4,1,fp);//读二进制速度文件
  float temp;
  temp=0;
  OnChange(v[i][ii][iii],temp);
  outfile<  }    
  outfile<  }
   }
fclose(fp);
return 0;
}

对于其他类型只需要修改对应的union类型就可以了,具体实现如下:

void OnChange(short InParam, short &OutParam)
{
union
{
char ch[2];
unsigned short iTemp;
}u,r;
u.iTemp = InParam;
r.ch[0] = u.ch[1];
r.ch[1] = u.ch[0];
OutParam = r.iTemp;
}


void OnChange(int InParam, int &OutParam)
{
union
{
char ch[4];
int iTemp;
}u,r;
u.iTemp = InParam;
r.ch[0] = u.ch[3];
r.ch[1] = u.ch[2];
r.ch[2] = u.ch[1];
r.ch[3] = u.ch[0];
OutParam = r.iTemp;
}


void OnChange(float InParam, float &OutParam)
{
union
{
char ch[4];
float iTemp;
}u,r;
u.iTemp = InParam;
r.ch[0] = u.ch[3];
r.ch[1] = u.ch[2];
r.ch[2] = u.ch[1];
r.ch[3] = u.ch[0];
OutParam = r.iTemp;
}


void OnChange(double InParam, double &OutParam)
{
union
{
char ch[8];
double iTemp;
}u,r;
u.iTemp = InParam;
r.ch[0] = u.ch[7];
r.ch[1] = u.ch[6];
r.ch[2] = u.ch[5];
r.ch[3] = u.ch[4];
r.ch[4] = u.ch[3];
r.ch[5] = u.ch[2];
r.ch[6] = u.ch[1];
r.ch[7] = u.ch[0];
OutParam = r.iTemp;
}

你可能感兴趣的:(C++)