Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C
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;
}
 
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 10-Apr-13 2:57am
Edited 10-Apr-13 3:00am
CPallini326.1K
v2
Comments
CHill60 at 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
good
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?
  Permalink  
Rate this: bad
good
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.
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 299
1 Maciej Los 295
2 Sergey Alexandrovich Kryukov 205
3 Aajmot Sk 202
4 Sinisa Hajnal 166
0 OriginalGriff 7,760
1 Sergey Alexandrovich Kryukov 7,072
2 DamithSL 5,604
3 Manas Bhardwaj 4,986
4 Maciej Los 4,785


Advertise | Privacy | Mobile
Web03 | 2.8.1411023.1 | Last Updated 10 Apr 2013
Copyright © CodeProject, 1999-2014
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