KnowledgeBase Archive

An Archive of Early Microsoft KnowledgeBase Articles

View on GitHub

Q32889: Toggling the Sign Bit on a Float or Double

Article: Q32889
Product(s): See article
Version(s): 3.00 4.00 5.00 5.10
Operating System(s): MS-DOS
Keyword(s): ENDUSER | | mspl13_c
Last Modified: 20-JUL-1988

Problem:
   I want to toggle the sign bit on a float or double by either
and'ing it with 0x7fff (make it positive) or or'ing it with 0x8000
(make it negative). However, the compiler will not accept the
following syntax:

   fl &= 0x7fff;
   fl |= 0x8000;

Response:
   The bitwise operators only works correctly with integral types; you
need to cast the float to be an integral type.
   The following are two macros that will allow you to toggle the sign
bit on a float or a double (note that the same thing can be
accomplished by multiplying the value by -1, but the macros are much
faster because they do not make any calls to the floating-point
library):

/* Macro to make either a float or a double Negative by setting sign bit */
#define NEG(arg) ((unsigned char *)&arg)[sizeof(arg)-1] |= \
                   (unsigned char)0x8000

/* Macro to make either a float or a double Positive by clearing sign bit */
#define POS(arg) ((unsigned char *)&arg)[sizeof(arg)-1] &= \
                   (unsigned char)0x7fff

THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Copyright Microsoft Corporation 1986-2002.