I am getting this error which indicates that there is something going wrong with a while loop somewhere. I step by step debugged through bit and for the arguments 0, 3 it returns -1 which is correct. I initialised the twoToThe array manually instead of using a while loop to avoid any potential errors so I am not sure if this is an error with multiply or with bit itself.
It checks the value inside of twoToThe to see if it and x are equal to 0, it then negates the result to get -1 if true.
function boolean bit(int x, int i) {
if (~((x & twoToThe[i]) = 0)) { return true; }
else { return false; }
}
This is how I am calling it in multiply, again this seems sound to me so I am not sure where the issue is stemming from.
function int multiply(int x, int y) {
var int sum, shiftedx, i;
let sum = 0;
let shiftedx = x;
let i = 0;
while (i < 16) {
// Check if i-th bit of y == 1
if (Math.bit(y, i)) { let sum = sum + shiftedx; }
let shiftedx = shiftedx + shiftedx;
let i = i + 1;
}
return sum;
}
I read this thread:
http://nand2tetris-questions-and-answers-forum.52.s1.nabble.com/stack-overflow-Math-bit-1-td4031389.html but since I am not using a while loop to initialise twoToThe I do not think this applies