Alex Rivera | Logout

Where would I use a bitwise operator in JavaScript?

Asked 2009-03-17T12:41:15.977
81

I've read 'what are bitwise operators?', so I know what bitwise operators are but I'm still not clear on how one might use them. Can anyone offer any real-world examples of where a bitwise operator would be useful in JavaScript?

Thanks.

Edit:

Just digging into the jQuery source I've found a couple of places where bitwise operators are used, for example: (only the & operator)

// Line 2756:
event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));

// Line 2101
var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
Edit
Report

1 Answer

13

Few other examples of how to use bitwise not and double bitwise not:

Floor operation

~~2.5    // 2
~~2.1    // 2
~~(-2.5) // -2

Check whether indexOf returned -1 or not

var foo = 'abc';
!~foo.indexOf('bar'); // true
answered 2012-06-12T16:15:48.330

Your Answer