Coffeescript-bitwise-operators

提供:Dev Guides
移動先:案内検索

CoffeeScript-ビット演算子

CoffeeScriptは次のビット演算子をサポートしています。 変数 A2 を保持し、変数 B3 を保持すると仮定します-

Sr.No Operator and Description Example
1

& (Bitwise AND)

整数引数の各ビットに対してブールAND演算を実行します。

(A & B) is 2.
2 *

(BitWise OR)*

整数引数の各ビットに対してブールOR演算を実行します。

(A B) is 3. 3

^ (Bitwise XOR)

整数引数の各ビットに対してブール排他的OR演算を実行します。 排他的ORは、オペランド1が真であるか、オペランド2が真であり、両方ではないことを意味します。

(A ^ B) is 1. 4

~ (Bitwise Not)

これは単項演算子であり、オペランドのすべてのビットを反転することにより動作します。

(~B) is -4. 5

<< (Left Shift)

第1オペランドのすべてのビットを、第2オペランドで指定された桁数だけ左に移動します。 新しいビットはゼロで埋められます。 値を1ポジション左にシフトすることは、2を乗算することと同等です。2ポジションをシフトすることは、4を乗算することと同等です。

(A << 1) is 4. 6

次の例は、CoffeeScriptでのビットごとの演算子の使用法を示しています。 このコードを bitwise_example.coffee という名前のファイルに保存します

a = 2 # Bit presentation 10
b = 3 # Bit presentation 11

console.log "The result of (a & b) is "
result = a & b
console.log result

console.log "The result of (a | b) is "
result = a | b
console.log result

console.log "The result of (a ^ b) is "
result = a ^ b
console.log result

console.log "The result of (~b) is "
result = ~b
console.log result

console.log "The result of (a << b) is "
result = a << b
console.log result

console.log "The result of (a >> b) is "
result = a >> b
console.log result
  • コマンドプロンプト*を開き、以下に示すように.coffeeファイルをコンパイルします。
c:/> coffee -c bitwise_example.coffee

コンパイル時に、次のJavaScriptが提供されます。

//Generated by CoffeeScript 1.10.0
(function() {
  var a, b, result;
  a = 2;
  b = 3;

  console.log("The result of (a & b) is ");
  result = a & b;
  console.log(result);

  console.log("The result of (a | b) is ");
  result = a | b;
  console.log(result);

  console.log("The result of (a ^ b) is ");
  result = a ^ b;
  console.log(result);

  console.log("The result of (~b) is ");
  result = ~b;
  console.log(result);

  console.log("The result of (a << b) is ");
  result = a << b;
  console.log(result);

  console.log("The result of (a >> b) is ");
  result = a >> b;
  console.log(result);

}).call(this);

次に、*コマンドプロンプト*を再度開き、以下に示すようにCoffeeScriptファイルを実行します。

c:/> coffee bitwise_example.coffee

CoffeeScriptファイルを実行すると、次の出力が生成されます。

The result of (a & b) is
2
The result of (a | b) is
3
The result of (a ^ b) is
1
The result of (~b) is
-4
The result of (a << b) is
16
The result of (a >> b) is
0