Bitwise operations in JavaScript

Don't you just love discovering new treasures?! Today I stumbled upon a Google/ex-Urchin javascript - urchin.js. Scrolling down the file with no apparent purpose in mind, I though I saw some >> and <<s. A second look? Yep, these do look like bitwise operators. In JavaScript? In the poor old insulted, sweared-upon, ignored, dumped to the juniors, forbidden, forgotten, no-good cheap status-bar-changing-only, blinking and blinding and obtrusive, cursor-following JavaScript. In the "abused, misunderstood, and kicked around like the poor step-child as known in fairytales" JavaScript (Dustin Diaz).

Yes, in (the reborn, beloved, the J in AJAX) Javascript, you can do bitwise operations, just like our grand-grand-dads did it in ANSI C ;) It's questionably useful, but who knows, life and projects come in all shapes. Personally I can't remember the last time I needed to bother with bitwise operations. (Ohm yes, I do, two days ago, working on an ANSI C to Java migration project :( )

Here's an example script (inspired by the PHP manual), that takes a hexadecimal color value, such as ff0088, parses it as 16 bit integer and then uses bitwise shifting to get the red, green and blue values from it.

var hex = 'ffaadd';
var rgb = parseInt(hex, 16); // value is 1675421


var red   = (rgb >> 16) & 0xFF; // returns 255
var green = (rgb >> 8) & 0xFF;  // 170
var blue  = rgb & 0xFF;		// 221	

And here's a demo to experiment with .

For the full list of available bitwise opearations (it's more or less the same as in PHP, Java, C++#>;-\) and for some more info, just do a search query.

This entry was posted on Friday, February 24th, 2006 and is filed under JavaScript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.


Get notification for future posts: follow me on Twitter or subscribe to my RSS feed

2 Responses to “Bitwise operations in JavaScript”

  1. Dan Dean Says:

    Nice little script! What would be the version of this for 3 digit hex colors?

  2. Al Says:

    “… cursor-following JavaScript.” Lol! Believe it’s more powerful now than back in 2006, especially with libraries like jQuery.

Leave a Reply