c++ - Convert big endian to little endian when reading from a binary file -
this question has answer here:
i've been looking around how convert big-endian little-endians. didn't find solve problem. seem there's many way can conversion. anyway following code works ok in big-endian system. how should write conversion function work on little-endian system well?
this homework, since systems @ school running big-endian system. it's got curious , wanted make work on home computer also
#include <iostream> #include <fstream> using namespace std; int main() { ifstream file; file.open("file.bin", ios::in | ios::binary); if(!file) cerr << "not able read" << endl; else { cout << "opened" << endl; int i_var; double d_var; while(!file.eof()) { file.read( reinterpret_cast<char*>(&i_var) , sizeof(int) ); file.read( reinterpret_cast<char*>(&d_var) , sizeof(double) ); cout << i_var << " " << d_var << endl; } } return 0; }
solved
so big-endian vs little-endian reverse order of bytes. function wrote seem serve purpose anyway. added here in case else need in future. double though, integer either use function torak suggested or can modify code making swap 4 bytes only.
double swap(double d) { double a; unsigned char *dst = (unsigned char *)&a; unsigned char *src = (unsigned char *)&d; dst[0] = src[7]; dst[1] = src[6]; dst[2] = src[5]; dst[3] = src[4]; dst[4] = src[3]; dst[5] = src[2]; dst[6] = src[1]; dst[7] = src[0]; return a; }
assuming you're going going on, it's handy keep little library file of helper functions. 2 of functions should endian swaps 4 byte values, , 2 byte values. solid examples (including code) check out this article.
once you've got swap functions, time read in value in wrong endian, call appropriate swap function. stumbling point people here single byte values not need endian swapped, if you're reading in character stream represents string of letters file, should go. it's when you're reading in value multiple bytes (like integer value) have swap them.
Comments
Post a Comment