问题
I'm using the GCC compiler (codeblocks) on windows, and the data I'm getting is from a UNIX machine, so it's all in big-endian. I have to swap it to little endian before I can us it. And I'll be dammed, but I can't get this to work. Using
temp = ntohl(fileBuf[N*i+j]);
or
_byteswap_ulong(fileBuf[N*i+j]);
returns nothing but zeroes. Which I know for a fact is incorrect.
The incoming data is just a string of 32bit integers (elevation data for part of the USA). Any help is greatly appreciated
EDIT: Pretty new here, I wasn't sure if the code would be useful
typedef unsigned char BYTE
int main()
{
long int temp;
int i,j;
ofstream myFile;
myFile.open("fixed4.txt");
const char *filePath = "input2";
BYTE *fileBuf;
FILE *file = NULL;
if ((file = fopen(filePath, "rb"))==NULL)
cout<< "File could not be opened successfully" << endl;
else
cout << "File Opened successfully" << endl;
long fileSize = getFileSize(file);
fileBuf = new BYTE[fileSize];
//BYTE *flipped;
//flipped = new BYTE[fileSize];
fread(fileBuf, fileSize, 4, file);
for (i=0; i<N; i+=1){
for (j=0; j<N; j+=1){
temp = _byteswap_ulong(fileBuf[N*i+j]);
grid[i][j]=binaryToBase10(temp);
// more code here but it isn't important....
回答1:
You don't give us much to go on, so this is a crystal-ball guess.
The type of fileBuf is char* or unsigned char*. So, the value you pass to ntohl is the single byte at location (i,j), not the 32-bit int at (i,j).
One way (there are better ways) to solve that problem is this:
ntohl( *(uint32_t*)&fileBuf[N*i+j] )
来源:https://stackoverflow.com/questions/11527763/byte-flipping-data-in-c-returns-only-zeroes