Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does x >>> 0 do? [duplicate]

Possible Duplicate:
What good does zero-fill bit-shifting by 0 do? (a >>> 0)

I've been trying out some functional programming concepts in a project of mine and I was reading about Array.prototype.map, which is new in ES5 and looks like this:

Array.prototype.map = function(fun) {
    "use strict";
    if (this === void 0 || this === null) {
        throw new TypeError();
    }
    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function") {
        throw new TypeError();
    }
    var res = new Array(len);
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
        if (i in t) {
            res[i] = fun.call(thisp, t[i], i, t);
        }
    }
    return res;
};

What I'm wondering is why it's doing t.length >>> 0. Because it doesn't seem to do anything. x >>> 0 //-> x! (as long as x is a number, obviously)

Also, note that I don't know how bitwise operators work.

like image 432
xj9 Avatar asked Nov 02 '10 19:11

xj9


People also ask

What does the operator >>> do?

The right shift operator ( >> ) returns the signed number represented by the result of performing a sign-extending shift of the binary representation of the first operand (evaluated as a two's complement bit string) to the right by the number of bits, modulo 32, specified in the second operand.

What is the meaning of X >> 1 in C?

This is a bitwise AND operation. x >>= 1 means "set x to itself shifted by one bit to the right". The expression evaluates to the new value of x after the shift. Note: The value of the most significant bit after the shift is zero for values of unsigned type.

What is N&1 in Java?

n & 1 will do a binary comparison between n, and 1 which is 00000000000000000000000000000001 in binary. As such, it will return 00000000000000000000000000000001 when n ends in a 1 (positive odd or negative even number) and 00000000000000000000000000000000 otherwise.

What is N 1 in coding?

At its most basic definition, N+1 simply means that there is a power backup in place should any single system component fail. The 'N' in this equation stands for the number of components necessary to run your system. The '+1' means there is one independent backup should a component of that system fail.


1 Answers

x >>> 0 performs a logical (unsigned) right-shift of 0 bits, which is equivalent to a no-op. However, before the right shift, it must convert the x to an unsigned 32-bit integer. Therefore, the overall effect of x >>> 0 is convert x into a 32-bit unsigned integer.

This ensures len is a nonnegative number.

js> 9 >>> 0
9
js> "9" >>> 0
9
js> "95hi" >>> 0
0
js> 3.6 >>> 0
3
js> true >>> 0
1
js> (-4) >>> 0
4294967292
like image 146
kennytm Avatar answered Oct 26 '22 20:10

kennytm