Click here to Skip to main content
13,045,790 members (47,076 online)
Rate this:
Please Sign up or sign in to vote.
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)
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;
        float r, s;
	r = 0;
	for (i = 0; i < NDATA; i++) {
		s = swapEnds(r);
		fwrite( &s, 1, 4, grib );
		r += (float)0.001;
Posted 10-Apr-13 1:57am
Updated 10-Apr-13 2:00am
CHill60 10-Apr-13 8:08am
I'd be wary of hard-coding the size of float as '4' - better to use sizeof(float)?
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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?
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web02 | 2.8.170713.1 | Last Updated 10 Apr 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100