I'm trying to understand the following code, found in MDN and in an answer of this related question. (Tested in FF 30 only.)
function createBinaryString (nMask) {
// nMask must be between -2147483648 and 2147483647
for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32;
nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
return sMask;
}
var p = createBinaryString(7);
console.log(p); //"00000000000000000000000000000111"
This one is on MDN, but how does this work - I'd appreciate any understandable explanation.
I have basic knowledge of binary operators and know, that there is a .toString(2)
method. But what does the String(nShifted >>> 31)
part do exactly?
Here are better readable versions, but the first one does not work. Here I also would appreciate any suggestion about what I'm doing wrong. I can't see any difference to the second, working version.
var re = '';
var numb = 7;
var shiftBuf = numb;
for (var i = 0; i < 32; i++); {
re += String(shiftBuf >>> 31);
shiftBuf <<= 1;
}
console.log(re); //"0"
var result = '';
var num = 7;
var shiftBuffer = num;
for (var i = 0; i < 32; i++) {
result += String(shiftBuffer >>> 31);
shiftBuffer <<= 1;
}
console.log(result); //"00000000000000000000000000000111"