[Javascript] RES: RES: RES: What operator is the circumflex accent(^) injavascript?

liorean liorean at gmail.com
Thu Aug 30 19:31:26 CDT 2007


On 30/08/2007, SosCpdGMail <soscpd at gmail.com> wrote:
> Bitwise is very low level programming. Very very fast. For a slow machine, in case of about 40, 50 different chars (keyboard keydown) to be recognized (lots of ifs/case, as you can see), it is useful, but for the most cases, no. Cell phones, PDA's still use it, but PC's are very powerful now.

The bitwise operators of JavaScript aren't particularly fast,
actually. Bitwise operations are integer operations, but JavaScript
doesn't have integers. So, what happens is that the engine takes the
operands, converts then to Numbers if they weren't already, then
converts those Numbers into an Int32s, does the bitwise operation on
those Int32s and gets an Int32 result, the turns that Int32 into a
Number, and returns that Number.





There's a few bitwise operations that are worth using in JavaScript,
but mostly that's limited to some special circumstances. let me give
you an example of one case where they can be at least slightly useful:
you can use numbers to store all three components of a colour value.
Like this:

    var
        colour = 0xcc33ff,
        red = (colour & 0xff0000) >>> 16, // => 204 == 0xcc
        green = (colour &0xff00) >> 8, // => 51 == 0x33
        blue = (colour &0xff); // => 255 === 0xff

And recombining:
    var
        red = 0x66,
        green = 0xff,
        blue = 0x00,
        colour =
            (red << 16) + (green << 8) + blue; // => 6749952 == 0x66ff00


Now, this is not something you'd usually do in JavaScript simply
because that's not how colours are stored in HTML or CSS, but it's at
least a possible use. You can use this to make conversion functions
from separate colours to #RRGGBB colour syntax and the other way
around, however.


Another case where these functions may be useful is if you're
unrolling loops using Duff's device.

    function unrolledloop(times,fn){
        var
            i = times & 8,
            j = times >> 3;
        while(i-->0)
            fn();
        while(j-->0){
            fn();
            fn();
            fn();
            fn();
            fn();
            fn();
            fn();
            fn();
        }
    }

And that is also a pretty dodgy thing indeed.




They're also great for dealing with flag vars, but also that is seldom
seen in JavaScript code.
-- 
David "liorean" Andersson



More information about the Javascript mailing list