On 21 mai, 11:29, Michael DOUBEZ <michael.dou...@free.fr> wrote:
> itdevries a écrit :
> > I'm trying to convert some char data I read from a binary
> > file (using ifstream) to a float type. I've managed to
> > convert the int types but now I need to do the float types
> > as well but it doesn't seem to work. The code below is what
> > I'm trying to use. Anyone see any obvious errors? or have
> > any hints/pointers?
> I suppose charBuf is of the type char[] ? In this case
> 'charBuf[ii] << offset' is 0 as soon as offset>=8 so you get
> only 0s.
Since when? That's not what my compiler does, and it's not what
the standard requires. In expressions, char's are promoted to
int's.
> > float floatRead = 0;
> > UINT32* ptr = (UINT32 *) (&floatRead);
> > int offset = 0;
> > for (int ii=startInd; ii<=endInd; ii++){
> > *ptr |= (charBuf[ii] << offset);
> > offset += 8;
> > };
Without seeing the other declarations, it's hard to say. What
is charBuf? Normally, I'd expect it to be an unsigned char*,
otherwise, the integral promotion of charBuf[ii] will extend the
sign, which will definitely not give you the results you want.
(If it's char*, you can always mask out the unwanted bits from
the extension, i.e.:
((charBuf[ ii ] & 0xFF) << offset)
You don't show startInd and endInd either. Obviously, they make
a difference.
When all is said and done, I'd unwind the loop:
*ptr = ((charBuf[ 0 ] & 0xFF) ) ;
*ptr |= ((charBuf[ 0 ] & 0xFF) <<

;
*ptr |= ((charBuf[ 0 ] & 0xFF) << 16) ;
*ptr |= ((charBuf[ 0 ] & 0xFF) << 24) ;
Note that you are also assuming that the representation of the
that you are reading more or less corresponds to the internal
representation on your machine (modulo byte order). This isn't
really something you can portably count on. (On the other hand,
doing it really right, in a 100% portable fashion, is relatively
difficult. I'd probably put in some sort of #if and and #error
to catch the case, and only add the complexity if the need
arose.)
> Your use of bitwise operator looks clumsy unless you have some
> logic to handle different byte ordering.
> What's wrong with
> memcpy(&floatRead,charBuf+startInd,sizeof(floatRea d));
> ?
Maybe the fact that it doesn't have the correct semantics? (It
might work, sometimes, but it's certainly a risky procedure.)
--
James Kanze (GABI Software) email:
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34