Visit Mozilla.org

Dokumentacja języka JavaScript 1.5:Operatory:Operatory bitowe

z Mozilla Developer Center, polskiego centrum programistów Mozilli.

UWAGA: Tłumaczenie tej strony nie zostało zakończone.
Może być ona niekompletna lub wymagać korekty.
Chcesz pomóc? | Dokończ tłumaczenie | Sprawdź ortografię | Więcej takich stron...

Spis treści

[edytuj] Podsumowanie

Operatory bitowe traktują swoje argumenty jako zbiory 32 bitów (zer i jedynek), a nie jak liczby dziesiętne, szesnastkowe, lub ósemkowe. Na przykład liczba dziesiętna dziewięć ma reprezentację bitową: 1001. Operatory bitowe dokonują swoich operacji na takich właśnie reprezentacjach dwójkowych, ale zwracają standardowe wartości liczbowe JavaScriptu.

Operatory
Zaimplementowany w: in: JavaScript 1.0
Wersja ECMA: ECMA-262

Następująca tabela podsumowuje operatory bitowe JavaScriptu:

Operator Użycie Opis
Bitowe AND a & b Returns a one in each bit position for which the corresponding bits of both operands are ones.
Bitowe OR a | b Returns a one in each bit position for which the corresponding bits of either or both operands are ones.
Bitowe XOR a ^ b Returns a one in each bit position for which the corresponding bits of either but not both operands are ones.
Bitowe NOT ~ a Inverts the bits of its operand.
Przesunięcie bitowe w lewo a << b Shifts a in binary representation b bits to the left, shifting in zeros from the right.
Przesunięcie bitowe w prawo a >> b Shifts a in binary representation b bits to the right, discarding bits shifted off.
Przesunięcie bitowe w prawo z wypełnieniem zerami a >>> b Shifts a in binary representation b bits to the right, discarding bits shifted off, and shifting in zeros from the left.

[edytuj] Signed 32-bit integers

The operands of all bitwise operators are converted to signed 32-bit integers in big-endian order and in two's complement format. Big-endian order means that the most significant bit (the bit position with the greatest value) is the left-most bit if the 32 bits are arranged in a horizontal line. Two's complement format means that a number's negative counterpart (e.g. 5 vs. -5) is all the number's bits inverted (bitwise NOT of the number, a.k.a. one's complement of the number) plus one. For example, the following encodes the integer 314 (base 10):

00000000000000000000000100111010

The following encodes ~314, i.e. the one's complement of 314:

11111111111111111111111011000101

Finally, the following encodes -314, i.e. the two's complement of 314:

11111111111111111111111011000110

The two's complement guarantees that the left-most bit is 0 when the number is positive and 1 when the number is negative. Thus, it is called the sign bit.

The number 0 is the integer that is composed completely of 0 bits.

The number -1 is the integer that is composed completely of 1 bits.

[edytuj] Bitowe operatory logiczne

Konceptualnie, operatory bitowe logiczne działają następująco:

  • Argumenty są konwertowane do 32-bitowej liczby całkowitej i wyrażone przez ciąg bitów (zer i jedynek).
  • Każdy bit w pierwszym argumencie jest dopasowany do odpowiedniego bitu w drugim argumencie: pierwszy bit do pierwszego bitu, drugi bit to drugiego bitu, i tak dalej.
  • Operator jest zastosowany do każdej pary bitów, i rezultat jest bitowy. .

[edytuj] & (Bitowe AND)

Performs the AND operation on each pair of bits. a AND b yields 1 only if both a and b are 1. The truth table for the AND operation is:

a b a AND b
0 0 0
0 1 0
1 0 0
1 1 1

Przykład:

     9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2)
                   --------------------------------
14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10)

Bitwise ANDing any number x with 0 yields 0.

Bitwise ANDing any number x with -1 yields x.

[edytuj] | (Bitowe OR)

Performs the OR operation on each pair of bits. a OR b yields 1 if either a or b is 1. The truth table for the OR operation is:

a b a OR b
0 0 0
0 1 1
1 0 1
1 1 1
     9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2)
                   --------------------------------
14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10)

Bitwise ORing any number x with 0 yields x.

Bitwise ORing any number x with -1 yields -1.

[edytuj] ^ (Bitowe XOR)

Performs the XOR operation on each pair of bits. a XOR b yields 1 if a and b are different. The truth table for the XOR operation is:

a b a XOR b
0 0 0
0 1 1
1 0 1
1 1 0

Przykład:

     9 (base 10) = 00000000000000000000000000001001 (base 2)
    14 (base 10) = 00000000000000000000000000001110 (base 2)
                   --------------------------------
14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10)

Bitwise XORing any number x with 0 yields x.

Bitwise XORing any number x with -1 yields ~x.

[edytuj] ~ (Bitowe NOT)

Performs the NOT operator on each bit. NOT a yields the inverted value (a.k.a. one's complement) of a. The truth table for the NOT operation is:

a NOT a
0 1
1 0

Przykład:

 9 (base 10) = 00000000000000000000000000001001 (base 2)
               --------------------------------
~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10)

Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.

[edytuj] Przesunięcie operatorów bitowych

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to 32-bit integers in big-endian order and return a result of the same type as the left operand.

[edytuj] << (Przesunięcie bitowe w lewo)

This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.

Na przykład, 9 << 2 yields 36:

     9 (base 10): 00000000000000000000000000001001 (base 2)
                  --------------------------------
9 << 2 (base 10): 00000000000000000000000000100100 (base 2) = 36 (base 10)

[edytuj] >> (Przesunięcie bitowe w prawo)

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name "sign-propagating".

Na przykład, 9 >> 2 yields 2:

     9 (base 10): 00000000000000000000000000001001 (base 2)
                  --------------------------------
9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)

Likewise, -9 >> 2 yields -3, because the sign is preserved:

     -9 (base 10): 11111111111111111111111111110111 (base 2)
                   --------------------------------
-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)

[edytuj] >>> (Przesunięcie bitowe w prawo z wypełnieniem zerami)

This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always positive.

For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. Na przykład, 9 >>> 2 yields 2, the same as 9 >> 2:

      9 (base 10): 00000000000000000000000000001001 (base 2)
                   --------------------------------
9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)

However, this is not the case for negative numbers. For example, -9 >>> 2 yields 1073741821, which is different than -9 >> 2 (which yields -3):

      -9 (base 10): 11111111111111111111111111110111 (base 2)
                    --------------------------------
-9 >>> 2 (base 10): 01111111111111111111111111111101 (base 2) = 1073741821 (base 10)

[edytuj] Przykłady

[edytuj] Przykład: Flags and bitmasks

The bitwise logical operators are often used to create, manipulate, and read sequences of flags, which are like binary variables. Variables could be used instead of these sequences, but binary flags take much less memory (by a factor of 32).

Suppose there are 3 flags:

  • flag A: we have an ant problem
  • flag B: we own a bat
  • flag C: we own a cat
  • flag D: we own a duck

These flags are represented by a sequence of bits: DCBA. When a flag is set, it has a value of 1. When a flag is cleared, it has a value of 0. Suppose a variable flags has the binary value 0101:

var flags = 0x5;   // binary 0101

This value indicates:

  • flag A is true (we have an ant problem);
  • flag B is false (we don't own a bat);
  • flag C is true (we own a cat);
  • flag D is false (we don't own a duck);

Since bitwise operators are 32-bit, 0101 is actually 00000000000000000000000000000101, but the preceding zeroes can be neglected since they contain no meaningful information.

A bitmask is a sequence of bits that can manipulate and/or read flags. Typically, a "primitive" bitmask for each flag is defined:

var FLAG_A = 0x1; // 0001
var FLAG_B = 0x2; // 0010
var FLAG_C = 0x4; // 0100
var FLAG_D = 0x8; // 1000

New bitmasks can be created by using the bitwise logical operators on these primitive bitmasks. For example, the bitmask 1011 can be created by ORing FLAG_A, FLAG_B, and FLAG_D:

var mask = FLAG_A | FLAG_B | FLAG_D; // 0001 | 0010 | 1000 => 1011

Individual flag values can be extracted by ANDing them with a bitmask, where each bit with the value of one will "extract" the corresponding flag. The bitmask masks out the non-relevant flags by ANDing with zeros (hence the term "bitmask"). For example, the bitmask 0100 can be used to see if flag C is set:

// if we own a cat
if (flags & FLAG_C) { // 0101 & 0100 => 0100 => true
   // do stuff
}

A bitmask with multiple set flags acts like an "either/or". For example, the following two are equivalent:

// if we own a bat or we own a cat
if ((flags & FLAG_B) || (flags & FLAG_C)) { // (0101 & 0010) || (0101 & 0100) => 0000 || 0100 => true
   // do stuff
}
// if we own a bat or cat
var mask = FLAG_B | FLAG_C; // 0010 | 0100 => 0110
if (flags & mask) { // 0101 & 0110 => 0100 => true
   // do stuff
}

Flags can be set by ORing them with a bitmask, where each bit with the value one will set the corresponding flag, if that flag isn't already set. For example, the bitmask 1010 can be used to set flags C and D:

// yes, we own a cat and a duck
var mask = FLAG_C | FLAG_D; // 0100 | 1000 => 1100
flags |= mask;   // 0101 | 1100 => 1101

Flags can be cleared by ANDing them with a bitmask, where each bit with the value zero will clear the corresponding flag, if it isn't already cleared. This bitmask can be created by NOTing primitive bitmasks. For example, the bitmask 1010 can be used to clear flags A and C:

// no, we don't neither have an ant problem nor own a cat
var mask = ~(FLAG_A | FLAG_C); // ~0101 => 1010
flags &= mask;   // 1101 & 1010 => 1000

The mask could also have been created with ~FLAG_A & ~FLAG_C (De Morgan's law):

// no, we don't have an ant problem, and we don't own a cat
var mask = ~FLAG_A & ~FLAG_C;
flags &= mask;   // 1101 & 1010 => 1000

Flags can be toggled by XORing them with a bitmask, where each bit with the value one will toggle the corresponding flag. For example, the bitmask 0110 can be used to toggle flags B and C:

// if we didn't have a bat, we have one now, and if we did have one, bye-bye bat
// same thing for cats
var mask = FLAG_B | FLAG_C;
flags = flags ^ mask;   // 1100 ^ 0110 => 1010

Finally, the flags can all be flipped with the NOT operator:

// entering parallel universe...
flags = ~flags;    // ~1010 => 0101