On Sun, 11 Apr 2010 00:30:07 -0400, Steven Schveighoffer <schvei...@yahoo.com> wrote:

Signed is probably trickier, suppose one is always negative and one is always positive!

Turns out signed is really easy once you have unsigned solved.

Here is minor and maxor for signed assuming unsigned is solved:

int maxor(int mina, int maxa, int minb, int maxb)
{
    if(mina < 0 && maxa >= 0)
    {
        int result = maxor(0, maxa, minb, maxb);
        return result > -1 ? result : -1;
    }
    if(minb < 0 && maxb >= 0)
    {
        int result = maxor(mina, maxa, 0, maxb);
        return result > -1 ? result : -1;
    }
return cast(int)maxor(cast(uint)mina, cast(uint)maxa, cast(uint)minb, cast(uint)maxb);
}

int minor(int mina, int maxa, int minb, int maxb)
{
    if(mina < 0 && maxa >= 0)
    {
        int result = minor(mina, -1, minb, maxb);
        return result < minb ? result : minb;
    }
    if(minb < 0 && maxb >= 0)
    {
        int result = minor(mina, maxa, minb, -1);
        return result < mina ? result : mina;
    }
return cast(int)minor(cast(uint)mina, cast(uint)maxa, cast(uint)minb, cast(uint)maxb);
}

The trick is to avoid dealing with a range that crosses the 0 boundary. The negative range isn't any different than an unsigned range -- set the most possible bits for max, unset the most possible bits for min. The sign bit simply becomes a hard-wired bit.

BTW, I release this code into the public domain, use it for any purpose you wish.

-Steve

Reply via email to