SHORT - Most Significant Bit?
Author Message
SHORT - Most Significant Bit?

What is the most straight forward way to check a SHORT if the MSB is set?

Thanks,
MS

Sun, 18 Dec 2005 01:02:30 GMT
SHORT - Most Significant Bit?

Quote:
>What is the most straight forward way to check a SHORT if the MSB is set?

Probably by being explicit and testing like this:

SHORT s;

if ( s & 0x8000 )

Alternatively (but less obviously):

if ( s < 0 )

Dave
--
MVP VC++ FAQ: http://www.mvps.org/vcfaq

Sun, 18 Dec 2005 03:19:02 GMT
SHORT - Most Significant Bit?
Thanks...

Quote:
> >What is the most straight forward way to check a SHORT if the MSB is set?

> Probably by being explicit and testing like this:

> SHORT s;

> if ( s & 0x8000 )

> Alternatively (but less obviously):

> if ( s < 0 )

> Dave
> --
> MVP VC++ FAQ: http://www.mvps.org/vcfaq

Sun, 18 Dec 2005 03:28:19 GMT
SHORT - Most Significant Bit?

Quote:
> What is the most straight forward way to check a SHORT if the MSB is set?

Given:

SHORT my_short;

If you truly have a SHORT, which is implicitly a signed data type, then
the test is unbelievably easy (even though it took me an embarrassing
amount of time to realize that):

if(my_short < 0) {
// if the number is negative, the MSB must be set
}

If you want a more general MSB test (which will work with both signed
and unsigned data types), you can try this instead:

#define MSB_FLAG(x) (1 << ((sizeof(x) << 3) - 1))

if(my_short & MSB_FLAG(my_short)) {
// msb is set
}

The definition of MSB_FLAG(x) looks a little complex, but it only
involves shifts and a subtraction, which compilers find trivial.  My
compiler (Metrowerks CodeWarrior Pro 8) distills MSB_FLAG(x) down to two
lines of assembly (one load, one store), and that's without any
optimizations enabled.  I expect that most other compilers out there
should also compare favorably.

Hope this helps.

Neil

Sun, 18 Dec 2005 04:00:34 GMT

 Page 1 of 1 [ 4 post ]

Relevant Pages