byte flipping data in C++ returns only zeroes

爷,独闯天下 提交于 2019-12-12 04:04:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!