Where would I use the bitwise operator in JavaScript?

I have read this one ( https://stackoverflow.com/a/3/75/16/ ), so I know that there are bitwise operators, but I still don’t understand how they can be used ... Can anyone suggest any real examples of where the beaten statement will be useful in JavaScript?

Thank.

Edit:

Just by going to the jQuery source . I found a couple of places where bitwise operators are used, for example: (only operator and 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; 
+51
javascript bitwise-operators
Mar 17 '09 at 12:41
source share
15 answers

Example:

Computes a hexadecimal value to obtain RGB color values.

 var hex = 'ffaadd'; var rgb = parseInt(hex, 16); // rgb is 16755421 var red = (rgb >> 16) & 0xFF; // returns 255 var green = (rgb >> 8) & 0xFF; // 170 var blue = rgb & 0xFF; // 221 
+46
Mar 17 '09 at 12:52
source share

I use bitwise operators heavily for numerical conversions in production scenarios because sometimes they are much faster than their Math or parseInt equivalents.

The price I have to pay is code readability . Therefore, I usually use Math in development and bitwise in production.

You can find some performance tricks at jsperf.com .

As you can see, browsers have not optimized Math.ceil and parseInt for many years, so I predict that bitwise will be faster and shorter than in furure .

Further reading on SO ...




Bonus: cheat sheet for | 0 | 0 : an easy and quick way to convert anything to an integer:

 ( 3|0 ) === 3; // it does not change integers ( 3.3|0 ) === 3; // it casts off the fractional part in fractionalal numbers ( 3.8|0 ) === 3; // it does not round, but exactly casts off the fractional part ( -3.3|0 ) === -3; // including negative fractional numbers ( -3.8|0 ) === -3; // which have Math.floor(-3.3) == Math.floor(-3.8) == -4 ( "3"|0 ) === 3; // strings with numbers are typecast to integers ( "3.8"|0 ) === 3; // during this the fractional part is cast off too ( "-3.8"|0 ) === -3; // including negative fractional numbers ( NaN|0 ) === 0; // NaN is typecast to 0 ( Infinity|0 ) === 0; // the typecast to 0 occurs with the Infinity ( -Infinity|0 ) === 0; // and with -Infinity ( null|0 ) === 0; // and with null, ( (void 0)|0 ) === 0; // and with undefined ( []|0 ) === 0; // and with an empty array ( [3]|0 ) === 3; // but an array with one number is typecast to number ( [-3.8]|0 ) === -3; // including the cast off of the fractional part ( [" -3.8 "]|0 ) === -3; // including the typecast of strings to numbers ( [-3.8, 22]|0 ) === 0 // but an Array with several numbers is typecast to 0 ( {}|0 ) === 0; // an empty object is typecast to 0 ( {'2':'3'}|0 ) === 0; // or a not empty object ( (function(){})|0 ) === 0; // an empty function is typecast to 0 too ( (function(){ return 3;})|0 ) === 0; 

and some kind of magic for me:

 3 | '0px' === 3; 
+31
Mar 27 '13 at 17:00
source share

In JavaScript, you can use double bitwise negation ( ~~n ) as a substitute for Math.floor(n) (if n is a positive number) or parseInt(n, 10) (even if n is negative). n|n and n&n always give the same results as ~~n .

 var n = Math.PI; n; // 3.141592653589793 Math.floor(n); // 3 parseInt(n, 10); // 3 ~~n; // 3 n|n; // 3 n&n; // 3 // ~~n works as a replacement for parseInt() with negative numbers… ~~(-n); // -3 (-n)|(-n); // -3 (-n)&(-n); // -3 parseInt(-n, 10); // -3 // …although it doesn't replace Math.floor() for negative numbers Math.floor(-n); // -4 

One bitwise negation ( ~ ) computes -(parseInt(n, 10) + 1) , so two bitwise negations return -(-(parseInt(n, 10) + 1) + 1) .

It should be noted that of these three alternatives, n|n seems to be the fastest .

Update: More precise steps: http://jsperf.com/rounding-numbers-down

(as published on a strange language function )

+24
Feb 08 '10 at 19:36
source share

Real life example?

^ (Bitwise XOR) as an I/O toggler

JsBin example

Used as value ^= 1 will change each time value called 0, 1, 0, 1 ...
If we pass this value as a Statement to the Conditional operator (?:) , for example,

 statement ? (if true) : (if false) 

and checking the logical representation 0=false, 1=true , we can switch the text, classes, styles .... all that is needed, for example, ie: button text:

 value ? "Close dropdown" : "Open dropdown"; 

For a single element , the Toggle function might look like this:

 // USING GLOBAL VARIABLE var tog = 0; var btn = document.getElementById('myButton'); function toggler(){ tog ^= 1; this.innerHTML = tog ? "hide" : "show"; } btn.addEventListener('click', toggler, false); 

For several elements, we can save the state of the tog variable directly in this - ElementHTML Object , for example:

 // WITHOUT GLOBAL VARIABLE var btns = document.getElementsByClassName('myButton'); function toggler(){ var tog = this.tog ^= 1; // get/set tog value out of this.tog object this.innerHTML = tog ? "hide" : "show"; } for(var i=0; i<btns .length; i++){ btns[i].addEventListener('click', toggler, false); } 

Or, if you don't like the idea of this , select the standard property of the dataset attribute;)

+13
Feb 27 '14 at 6:58
source share

Given the success that Javascript is making (especially with nodejs, which allows server-side programming using js), JS is increasingly complicated code. Here are some examples where I used bitwise operators:

  • IP address operations:

     //computes the broadcast address based on the mask and a host address broadcast = (ip & mask) | (mask ^ 0xFFFFFFFF) //converts a number to an ip adress sprintf(ip, "%i.%i.%i.%i", ((ip_int >> 24) & 0x000000FF), ((ip_int >> 16) & 0x000000FF), ((ip_int >> 8) & 0x000000FF), ( ip_int & 0x000000FF)); 

Note: this is C code, but JS is almost identical

  • CRC algorithms often use them

Check out the wikipedia entry on this

  • Screen Resolution Operations
+11
Mar 17 '09 at 12:49
source share

To indicate whether a number is odd:

 function isOdd(number) { return !!(number & 1); } isOdd(1); // true, 1 is odd isOdd(2); // false, 2 is not odd isOdd(357); // true, 357 is odd 

Faster than a module - use where performance really counts!

+11
Jun 27 '14 at 19:39
source share

A few other examples of using bitwise and double bitwise are not:

Floor work

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

Check if indexOf -1 is returned or not

 var foo = 'abc'; !~foo.indexOf('bar'); // true 
+10
Jun 12 '12 at 16:15
source share

You can use them to display a boolean:

 var foo = 1; var bar = 0; alert(foo ^= 1); alert(bar ^= 1); 

This is a little silly, although for the most part, bitwise operators do not have a large number of applications in Javascript.

+9
Mar 17 '09 at 12:49
source share

Bitmasks .

Used widely, for example, in JS events.

+6
Mar 17 '09 at 12:50
source share
 var arr = ['abc', 'xyz'] 

It is annoying to write

 if (arr.indexOf('abc') > -1) { // 'abc' is in arr } if (arr.indexOf('def') === -1) { // 'def' is not in arr } 

check something inside an array?

You can use the bitwise ~ operator as follows:

 if (~arr.indexOf('abc')) { // 'abc' is in arr } if (! ~arr.indexOf('def')) { // 'def' is not in arr } 
+5
Jan 18 '16 at 10:35
source share

I used it once for a permission widget . File permissions on unix is ​​a bitmask, so you need to use bitwise operations to parse it.

+2
Mar 17 '09 at 12:52
source share

I use them to smooth out three numbers in 1 as a way to store multidimensional arrays in Uint16Array . Here is a snippet of the voxel game that I am developing:

 function Chunk() { this._blocks = new Uint16Array(32768); this._networkUpdates = []; } Chunk.prototype.getBlock = function(x, y, z) { return this._blocks[y + (x << 5) + (z << 10)]; }; Chunk.prototype.setBlock = function(x, y, z, value) { this._blocks[y + (x << 5) + (z << 10)] = value; this._networkUpdates.push(value + (y << 15) + (x << 20) + (z << 25)); }; Chunk.prototype.getUpdates = function() { return this._networkUpdates; }; Chunk.prototype.processUpdate = function(update) { // this._blocks[Math.floor(update / 65536)] = update % 65536; this._blocks[update >> 16] = update & 65535; }; var chunk = new Chunk(); chunk.setBlock(10, 5, 4); alert(chunk.getBlock(10, 5, 4)); alert(chunk.getUpdates()[0]); 
+1
Mar 29 '15 at 8:43
source share

They seem very useful when you work with hexadecimal values ​​and bits. Since 4 bits can represent from 0 to F.

1111 = F 1111 1111 = FF.

0
Nov 12 '13 at 5:41
source share

Node.js example

Assuming you have a file (called multiply.js) with this content, you can run

 `node multiply <number> <number>` 

and get a conclusion consistent with the use of the multiplication operator on the same two numbers. Switching bits in a Mulitply function is an example of how to take a bit mask representing one number and use it to flip bits in another number for quick operations.

 var a, b, input = process.argv.slice(2); var printUsage = function() { console.log('USAGE:'); console.log(' node multiply <number> <number>'); } if(input[0] === '--help') {+ printUsage(); process.exit(0); } if(input.length !== 2) { printUsage(); process.exit(9); } if(isNaN(+input[0]) || isNaN(+input[1])) { printUsage(); process.exit(9); } // Okay, safe to proceed a = parseInt(input[0]), b = parseInt(input[1]); var Multiply = function(a,b) { var x = a, y = b, z = 0; while( x > 0 ) { if(x % 2 === 1) { z = z + y; } y = y << 1; x = x >> 1; } return z; } var result = Multiply(a,b); console.log(result); 
0
Apr 09 '15 at 23:00
source share

I just found this question trying to confirm if the bitwise AND operator was also & in Javascript.

Since you asked for an example:

 if ($('input[id="user[privileges]"]').length > 0) { $('#privileges button').each(function () { if (parseInt($('input[id="user[privileges]"]').val()) & parseInt($(this).attr('value'))) { $(this).button('toggle'); } }); } 

It fills the state of the buttons with jQuery, given the value of the bit mask of the hidden field:

  • none = 0
  • user = 1
  • administrator = 2
  • user + administrator = 3
-one
Jul 16 '13 at 4:04 on
source share



All Articles