robertwessel2@yahoo.com a écrit :
Quote:
>
On Jan 24, 11:07 pm, Michael DOUBEZ <michael.dou...@free.frwrote:
Quote:
>Chris Stankevitz a écrit :
>>
Quote:
>>Is this a fast way to invert a float:
>>inline Invert(float& f)
>>{
>> f *= -1.0f;
>>}
>>I'd like the CPU to flip the sign bit (and not carry out a float-float
>>multiplication). Please enlighten me! I'm going be performing a lot
>>of these.If you don't mind portability, you can simply flip it:
>reinterpret_cast<char*>(&f)[sizeof(float)-1]^=0x80;
>>
>This is evil.
>
>
Not only is it not portable, it doesn't work on (probably) the majority
of architectures out there. Mind you that the OP did not specify that
he was running on x86 or another machine which has IEEE-like floats
stored little endian. Even worse, your code may be substantially
slower than just a straight multiplication by -1 or negation since it
will almost certainly force the compiler to actually store the value in
memory before flipping the bit - something that would likely be avoided
if the value was already in a register, and the function actual got (as
requested) inlined. All quite implementation dependent, of course.
>
Yes, it is evil. But, if you do something implementation dependant, well
you just do it.
And I expect this kind of trick to work on IEEE, IBM and VAX float since
they all put the sign bit on the MSB. Making a switch for litlle/big
endian is not really a big deal.
Concerning the perfs, I didn't make any bench but the truth is that bit
operations on float are forbidden so unless the compiler optimize the
operation (-() or *-1.0f) alternatives are equivalent.
Now, this is not something I would do but worth a try.
Michael