Где бы я использовал побитовый оператор в JavaScript? - PullRequest
68 голосов
/ 17 марта 2009

Я прочитал 'что такое побитовые операторы?' , поэтому я знаю , что такое побитовые операторы , но я до сих пор не понимаю, как может использовать их. Кто-нибудь может предложить какие-нибудь реальные примеры того, где побитовый оператор был бы полезен в JavaScript?

Спасибо.

Edit:

Просто копаясь в jQuery-источнике Я нашел пару мест, где используются побитовые операторы, например: (только оператор &)

// 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;

Ответы [ 16 ]

3 голосов
/ 17 марта 2009

Я использовал его один раз для виджета разрешений . Права доступа к файлам в Unix являются битовой маской, поэтому для ее анализа необходимо использовать битовые операции.

2 голосов
/ 19 марта 2018

Этот ответ содержит объяснения Ответ Марка .

Прочитав эти объяснения и выполнив фрагмент кода, можно получить идею.

var hex = 'ffaadd';
var rgb = parseInt(hex, 16); // rgb value is 16755421 in decimal = 111111111010101011011101 in binary = total 24 bits


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

// HOW IS IT

// There are two bitwise operation as named SHIFTING and AND operations.
// SHIFTING is an operation the bits are shifted toward given direction by adding 0 (zero) bit for vacated bit fields.
// AND is an operation which is the same with multiplying in Math. For instance, if 9th bit of the given first bit-set is 0
// and 9th bit of the given second bit-set is 1, the new value will be 0 because of 0 x 1 = 0 in math.

// 0xFF (000000000000000011111111 in binary) - used for to evaluate only last 8 bits of a given another bit-set by performing bitwise AND (&) operation. 
// The count of bits is 24 and the first 16 bits of 0xFF value consist of zero (0) value. Rest of bit-set consists of one (1) value.
console.log("0xFF \t\t\t\t: ", 0xFF) 


// 111111111010101011011101 -> bits of rgb variable
// 000000000000000011111111 -> 255 after (rgb >> 16) shifting operation
// 000000000000000011111111 -> 255 complement (changes the first 16 bits and does nothing for the last 8 bits)
// 000000000000000011111111 -> result bits after performing bitwise & operation
console.log("Red - (rgb >> 16) & 0xFF \t: ", (rgb >> 16) & 0xFF) // used for to evaluate the first 8 bits

// 111111111010101011011101 -> bits of rgb variable
// 000000001111111110101010 -> 65450 -> 'ffaa'
// 000000000000000011111111 -> 255 complement (changes the first 16 bits and does nothing for the last 8 bits)
// 000000000000000010101010 -> result bits after performing bitwise & operation
// calculation -> 000000001111111110101010 & 000000000000000011111111 = 000000000000000010101010 = 170 in decimal = 'aa' in hex-decimal
console.log("Green - (rgb >> 8) & 0xFF \t: ", (rgb >> 8) & 0xFF) // used for to evaluate the middle 8 bits 

// 111111111010101011011101 -> 'ffaadd'
// 000000000000000011111111 -> 255 complement (changes the first 16 bits and does nothing for the last 8 bits)
// 000000000000000011011101 -> result bits after performing bitwise & operation 
// calculation -> 111111111010101011011101 & 000000000000000011111111 = 221 in decimal = 'dd' in hex-decimal
console.log("Blue - rgb & 0xFF \t\t: ", rgb & 0xFF) // // used for to evaluate the last 8 bits.

console.log("It means that `FFAADD` hex-decimal value specifies the same color with rgb(255, 170, 221)")

/* console.log(red)
console.log(green)
console.log(blue) */
2 голосов
/ 29 марта 2015

Я использую их, чтобы сгладить три числа в 1 для хранения многомерных массивов в Uint16Array . Вот фрагмент воксельной игры, которую я разрабатываю:

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]);
0 голосов
/ 10 апреля 2015

Пример использования Node.js

Если у вас есть файл (называемый multiply.js) с этим содержимым, вы можете запустить

`node multiply <number> <number>`

и получите вывод, совместимый с использованием оператора умножения для тех же двух чисел. Сдвиг битов, происходящий в функции Mulitply, является примером того, как взять битовую маску, представляющую одно число, и использовать ее для переворачивания битов в другое число для быстрых операций.

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 голосов
/ 12 ноября 2013

Они кажутся очень полезными, когда вы работаете с шестнадцатеричными значениями и битами. Поскольку 4 бита могут представлять от 0 до F.

1111 = F 1111 1111 = FF.

0 голосов
/ 16 июля 2013

Я только что нашел этот вопрос, пытаясь подтвердить, был ли побитовый оператор AND также & в Javascript.

Так как вы попросили пример:

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');
        }
    });
}

Заполняет состояние кнопок с помощью jQuery, учитывая битовую маску скрытого поля:

  • none = 0
  • user = 1
  • administrator = 2
  • user + administrator = 3
...