Toán tử bitwise và ứng dụng trong Javascript

  1. Chuyển string thành số nguyên:
    ~~"42" // Result: 42
  2. Kiểm tra substring trong string:
    if(~'parent string'.indexOf('string')){
    	console.log('string is in parent string!');
    }
  3. Kiểm tra chẵn lẻ:
    var x = 3;
    if(!(x & 1)){
    	console.log(x + ' is even!');
    }else{
    	console.log(x + ' is odd!');
    }
  4. Swap 2 numbers:
    var a = 42;
    var b = 69;
    a^=b, b^=a, a^=b;
    // Result: a: 69, b: 42
    
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s