views:

186

answers:

2

Here's an example I ran across:

private function bitwiseAnd(a:int, b:int):int {
    var result:int = 0;
    var n:int = 1;
    while ((a > 0) && (b > 0)) {
        if (((a % 2) == 1) && ((b % 2) == 1)) {
            result += n;    
        }
        a = a / 2;
        b = b / 2;
        n = n * 2;
    }
    return result;
}

So basically all I need then is bitwiseOr and bitwiseNot and I'm set.
The reason is that Pixel Bender doesn't support bitwise ops (inexplicably) but does support various math operations. Also they don't support loops for Flash either, but the above can just be expanded out.

I thought about doing bitwise ops without bitwise operators a while back, but couldn't picture how to do it. I wouldn't know how the above was derived logically either.

+3  A: 

Seems like a basic exercise - especially 'OR' (change 2 appearances of '&&' to '||'):

private function bitwiseOr(a:int, b:int):int {
    var result:int = 0;
    var n:int = 1;
    while ((a > 0) || (b > 0)) {
        if (((a % 2) == 1) || ((b % 2) == 1)) {
            result += n;    
        }
        a = a / 2;
        b = b / 2;
        n = n * 2;
    }
    return result;
}

There's a bit more work to do with Not - because you can't stop the loop early and you need to know how many bits to deal with. The final problem is how to deal with the sign bit; that needs to be flipped too. Ideally, we'd use unsigned integers - I'm not sure whether they are an option. This code avoids the issues: it flips 31 bits, leaving the 32nd bit as an exercise for the reader.

private function bitwiseNot(a:int):int {
    var result:int = 0;
    var n:int = 1;
    var i:int = 0;
    while (i < 31)  {
        if ((a % 2) == 0) {
            result += n;    
        }
        a = a / 2;
        n = n * 2;
        i++;
    }
    return result;
}
Jonathan Leffler
To flip the sign bit, replace "return result;" with "return result + 1<<31";
Igor ostrovsky
Hey thanks everyone for the instant feedback (this forum is amazing) but as I said I realized the problem wasn't a big deal almost immediately after I wrote the question. But I will look at all the posts provided. Thanks again.
But << is a bitwise operator
Carson Myers
A: 

Hey thanks everyone for the instant feedback (this forum is amazing) but as I said I realized the problem wasn't a big deal almost immediately after I wrote the question. But I will look at all the posts provided. Thanks again. –