将文件从Little endian转换为Big endian [英] Convert a file from Little endian to Big endian

查看:106
本文介绍了将文件从Little endian转换为Big endian的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我需要在Linux 32位下将文件从Little Endian转换为Big Endian。我知道我可以自己做这个程序,但我想知道是否已经完成了任何可以完成工作的程序。



提前谢谢

Hi,

I need to convert a file from Little Endian to Big Endian under Linux 32 bit. I know that I can do the program myself, but I was wondering if there is any program already done that can do the job.

Thanks in advance

推荐答案

Endianness是指数据类型中的BYTE排序,因此你的问题很模糊。

如果是某种二进制文件,你需要读取每个结构进入并反转其中的BYTES,然后序列化回磁盘。如果它是某种多字节文本文件,你需要查找编码并采取相应的行动。



旁注:如果要在文件中交换字节对,请使用dd与

conv = swab



LE:尝试这样做只是为了扭转一切:



Endianness refers to BYTE ordering within data types, hence your question is vague.
If it's some sort of binary file, you need to read every structure in and reverse the BYTES in it, then serialize back to disk. If it's some sort of multibyte text file you need to lookup the encoding and act accordingly.

sidenote: If you want to swap pairs of bytes in a file use dd with
conv=swab

LE: try this for just reversing everything:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
  FILE* input = NULL;
  FILE* output = NULL;
  unsigned long size = 0;
  unsigned long itr = 0;
  unsigned char* buffer;


  if(argc != 3)
    return 0;
  input = fopen(argv[1],"rb");
  output = fopen(argv[2],"wb");
  
  if(!input || !output)
    fprintf(stderr,"could not open file");
  fseek(input,0,SEEK_END);
  size = ftell(input);
  fseek(input,0,SEEK_SET);

  buffer = (unsigned char*)malloc(size);
  
  fread(buffer,1,size,input);
  fclose(input);
  for(itr = size;itr>0;itr--)
  {
    fwrite(&buffer[itr-1],1,1,output);
  }
  fclose(output);
return 0;
}





编译和使用如下:



./application inputfile outputfile



compile and use like this:

./application inputfile outputfile


@ slack7219723



这是我正在寻找的解决方案。我略微修改你的代码来获得这个



@slack7219723

This is the solution that I was looking for. I modify slightly your code to obtain this

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
    FILE* input = NULL;
    FILE* output = NULL;
    unsigned long size = 0;
    unsigned long itr = 0;
    unsigned char* buffer;

    if(argc != 3)
    return 0;
    input = fopen(argv[1],"rb");
    output = fopen(argv[2],"wb");

    if(!input || !output)
        fprintf(stderr,"could not open file");
    fseek(input,0,SEEK_END);
    size = ftell(input);
    fseek(input,0,SEEK_SET);

    buffer = (unsigned char*)malloc(size);

    fread(buffer,1,size,input);
    fclose(input);
    for(itr = 0;itr<size;itr=itr+4)
    {
        fwrite(&buffer[itr + 3],1,1,output);
        fwrite(&buffer[itr + 2],1,1,output);
        fwrite(&buffer[itr + 1],1,1,output);
        fwrite(&buffer[itr + 0],1,1,output);
    }
    fclose(output);
    return 0;
}


这篇关于将文件从Little endian转换为Big endian的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆