C ++中的字节翻转数据只返回零 [英] byte flipping data in C++ returns only zeroes
问题描述
我在Windows上使用GCC编译器(代码块),我得到的数据来自UNIX机器,所以它都是大端的。我必须先将它交换成小端,然后才能使用它。我会被阻止,但我无法得到这个工作。使用
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; ((file = fopen(filePath,rb))== NULL)
cout<< 文件无法成功打开<< ENDL;
else
cout<< 文件已成功打开<< ENDL;
long fileSize = getFileSize(file);
fileBuf = new BYTE [fileSize];
// BYTE *翻转;
//翻转=新BYTE [fileSize];
fread(fileBuf,fileSize,4,file);
为(I = 0; I< N; I + = 1){
。对于(j = 0; J< N; J + = 1){
温度= _byteswap_ulong( fileBuf [N * I + J]);
grid [i] [j] = binaryToBase10(temp);
//这里有更多的代码,但它并不重要....
你不会让我们继续下去,所以这是一个水晶球的猜测。
fileBuf
是 char *
或 unsigned char *
。因此,您传递给 ntohl
的值是位置(i,j)处的单字节,而不是位于(i, j)。
解决这个问题的一种方法(有更好的方法)是这样的:
pre > 再用ntohl(*(uint32_t的*)及fileBuf [N * I + J])
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....
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] )
这篇关于C ++中的字节翻转数据只返回零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!