From: Martin Bonner (martin.bonner_at_[hidden])
Date: 2006-08-03 09:37:04
[mailto:boost-bounces_at_[hidden]] On Behalf Of Johan Råde Sent: 03
August 2006 12:38 To: boost_at_[hidden]
Subject: Re: [boost] Portable signbit macro/function?
> John Maddock wrote:
>> And the endianness of the float's if you're doing bit testing. But
>> of course if there is a macro already it's easy enough to convert it
>> into a function.
> The following function does bit testing, without advance knowledge of
> which bit is the sign bit. The function figures out on its own, at
> compile time, which bit is the sign bit. Hence you do not have to
> about IEEE 754 and endianness. The only thing that is required is that
> sizeof(float) == sizeof(int).
It also requires that the sign bit of the float is in the same place as the sign bit of the int ... which it is for most usual implementations of IEEE 754 (although I'm not sure if the standard actually refers to byte ordering issues), but I don't think it is true for Vax floating point formats.
> bool signbit(float x)
> const float one = 1;
> const float neg_one = -1;
> const int sign_mask = reinterpret_cast<const int&>(one)
> ^ reinterpret_cast<const int&>(neg_one);
> return reinterpret_cast<int&>(x) & sign_mask;
> I have tested it on VC++ 7.1 with signed zeroes, signed infinities and
> signed NaNs, and plain signed numbers.
Can I suggest that you study the tenth commandment for C programmers at http://www.lysator.liu.se/c/ten-commandments.html. C++ avoids the need for some of those commandments, but that one has stood the test of time with undiminished force.
-- Martin Bonner Martin.Bonner_at_[hidden] Pi Technology, Milton Hall, Ely Road, Milton, Cambridge, CB4 6WZ, ENGLAND Tel: +44 (0)1223 203894
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk