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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With