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  
 
 [ 4 post ] 

 Relevant Pages 

1. Most significant bit algorithm

2. most significant bit, leading zeros

3. Most significant bit algorithm

4. bit fields (int vs. unsigned short)

5. Bit fields & short: conversion

6. 32-bit shorts (was a long long title)

7. 16 bit code - Long filename to short

8. Shortest Short

9. 64 Bit * 64 Bit = 128 Bit

10. 32 bit Icons and C# VS.net (24 bit + 8 bit alpha)

11. float and double: # significant bits

12. Significant digits for FP comparisons...

 

 
Powered by phpBB® Forum Software