Skip to content

Instantly share code, notes, and snippets.

@drewstaylor
Last active May 15, 2025 13:17
Show Gist options
  • Save drewstaylor/a44cf529ec509dd5273aa72b94948e22 to your computer and use it in GitHub Desktop.
Save drewstaylor/a44cf529ec509dd5273aa72b94948e22 to your computer and use it in GitHub Desktop.
Convert a file from little endian to big endian and vice versa
// usage:
// ./endian_swap infile.lsb.ext outfile.msb.ext
// ./endian_swap infile.msb.ext outfile.lsb.ext
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment