Bitwise operations in JavaScript

February 24th, 2006. Tagged: 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.

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov