C++中的字节翻转数据只返回零

byte flipping data in C++ returns only zeroes

本文关键字:返回 数据 翻转 字节 C++      更新时间:2023-10-16

我在windows上使用GCC编译器(代码块),我得到的数据来自UNIX机器,所以都是big-endian。我必须先把它换成小endian,然后才能给我们。我会被诅咒的,但我无法让它发挥作用。使用

temp = ntohl(fileBuf[N*i+j]);

_byteswap_ulong(fileBuf[N*i+j]);

只返回零。我所知道的事实是不正确的。

传入的数据只是一个32位整数的字符串(美国部分地区的高程数据)。非常感谢任何帮助

编辑:这里很新,我不确定这个代码是否对有用

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....

您没有给我们太多内容,所以这是一个水晶球猜测。

fileBuf的类型是char*unsigned char*。因此,传递给ntohl的值是位置(i,j)处的单字节,而不是(i,j)处的32位int。

解决这个问题的一种方法(有更好的方法)是:

ntohl( *(uint32_t*)&fileBuf[N*i+j] )