Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Have to swap big/little endian and write out for a program running on another machine.

When I read the file on the other machine, it will usually read the first 360 floats correctly but then starts reading unknown numbers. The unknown numbers are always the same so it's not corrupted. Then near the end of the file, it starts reading the floats correctly again.

Any ideas? Is fwrite somehow not writing out all the bytes?

Here's the (abbreviated) code (running on MS VC 10 - 4 byte float)
C
float swapEnds(float littleE)
{
	float bigE;
	unsigned char *a, *b;

	a = (unsigned char *) &littleE;
	b = (unsigned char *) &bigE;

	b[0] = a[3];
	b[1] = a[2];
	b[2] = a[1];
	b[3] = a[0];

	return bigE;
}

main()
{
        float r, s;
...
	r = 0;
	for (i = 0; i < NDATA; i++) {
		s = swapEnds(r);

		fwrite( &s, 1, 4, grib );

		r += (float)0.001;
	}
...
}
Posted
Updated 10-Apr-13 2:00am
v2
Comments
CHill60 10-Apr-13 8:08am    
I'd be wary of hard-coding the size of float as '4' - better to use sizeof(float)?

Conversion code looks correct (you may verify it comparing its results with the ones of the ntohl[^] function).
Are you sure the original file contains all well-formed floats?
 
Share this answer
 
If it reads the first 360 fine, then has a problem, then works again, it's unlikely to be the endian swap routine that is at fault. And 360 is not a special number, even when looked at as 1440 - the size in bytes.

Have you looked at the data? Is there any obvious change in data patterns around the 1440th byte? How big is the "bad area"? How big is the "good area" at the end? Is the file opened as binary, or text? Could it be that the reading software does not like some part of the data?

Sorry not to give you an answer, but I think you need more investigation before any kind of true answer can be given.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900