John wrote:

> I have two numbers a,b.

>

> I would like to compare if most significant bit of a is

> larger than most significant bit of b. Right now the code

> I am using looks like this

>

> int w1,w2;

> asm("bsr %0,%1" : "=r" (w1) : "r" (a));

> asm("bsr %0,%1" : "=r" (w2) : "r" (b));

> return w1 < w2;

>

> Anyone has any better ideas on how to do this. Seems

> like this code is pretty slow. Is there an easier way

> to compare the msb of two numbers? Maybe using one

> assembly command? Or maybe by doing something else

> compared to bsr?

>

> Thanks,

> --j

>
The safest method is to extract the most significant

bits and compare them. This becomes a bit tricky

with different bit-widths of variables and also

for Endianism.

In a header file, <limits.h>, is a symbol CHAR_BIT,

which defines the number of bits in the type char.

The "sizeof" operator will return the number of

units (of type char) of a type or structure.

Knowing this, the number of bits in an integer

can be found.

Let's define the most significant bit (MSB) as:

msb = 1 << ((sizeof(int) * CHAR_BIT) - 1)

which is a 1 left shifted to one less than the

number of bits in an integer.

The MSB can be isolated using this information

and the bitwise AND operator.

However, setting up the relationship in a truth

table yields:

---------+----------+-------

MSB of A | MSB of B | A > B

---------+----------+-------

0 | 0 | False (0)

---------+----------+-------

0 | 1 | False (0)

---------+----------+-------

1 | 0 | True (1)

---------+----------+-------

1 | 1 | False (0)

---------+----------+-------

result = msb_a AND NOT msb_b.

The implementation of this is left as an exercise

for the O.P.

--

Thomas Matthews

C++ newsgroup welcome message:

http://www.slack.net/~shiva/welcome.txt
C++ Faq:

http://www.parashift.com/c++-faq-lite
C Faq:

http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:

http://www.comeaucomputing.com/learn/faq/
Other sites:

http://www.josuttis.com -- C++ STL Library book

http://www.sgi.com/tech/stl -- Standard Template Library