ngogo wrote
I was wondering whether there is an efficient way of implementing division by powers of 2 would be, not having shifting as part of our language.
The hardware cannot do right shifting so you pretty much stuck with bit testing and addition. You might be able to get some improvement using something like
// UNTESTED CODE
class Math {
static Array power2;
function int div2n (int x, int n) {
// Needs code to deal with negative numbers. Fastest might be to make
// a version of the algorithm that only handles negatives. Same as this
// but starts with -1 and sets 0's instead of 1's.
var int test, set;
var int y; // init = 0
// RANGE CHECK n -- return 0 if n>15, call mul2n() if n<0
let set = 1;
let test = power2[n]; // global inited in Math.init()
while (~(test=0)) {
if ((x&test)=test) {
let y = y | set;
}
let test = test+test; // Signed overflow is OK here
let set = set+set; // Signed overflow is OK here
}
return y;
}
}
--Mark