Bitwise operations without bitwise operators

Here's an example I ran into:

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 is bitwiseOr and bitwiseNot and I have it installed.
The reason is that Pixel Bender does not support bitwise operations (inexplicably), but it does support various math operations. In addition, they also do not support loops for Flash, but the above can simply be extended.

I thought about doing bitwise operations without bitwise operators a while ago but couldn't figure out how to do it. I wouldn't know how it was deduced.

+2


source to share


1 answer


Sounds like a basic exercise - especially "OR" (changing 2 occurrences 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;
}

      



With Not, it's a little more work because you can't stop the loop early and you need to know how many bits to have. The last problem is how to deal with the sign bit; which also needs to be flipped. Ideally we'll use unsigned integers - I'm not sure if they are an option. This code avoids problems: it flips 31 bits, leaving 32 bits 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;
}

      

+5


source







All Articles