CoffeeScript - 按位运算符

CoffeeScript 支持以下位运算符。 假设变量A包含2,变量B包含3,则 −

Sr.No 运算符及说明 示例
1

& (按位与)

它对其整数参数的每一位执行布尔与运算。

(A & B) is 2.
2

| (按位或)

它对其整数参数的每一位执行布尔或运算。

(A | B) is 3.
3

^ (按位异或)

它对其整数参数的每一位执行布尔异或运算。 异或表示操作数一为真或操作数二为真,但不能同时为真。

(A ^ B) is 1.
4

~ (按位非)

它是一个一元运算符,通过反转操作数中的所有位来进行运算。

(~B) is -4.
5

<< (左移)

它将第一个操作数中的所有位向左移动第二个操作数中指定的位数。 新位用零填充。 将一个值左移一位相当于乘以 2,左移两位相当于乘以 4,依此类推。

(A << 1) is 4.
6

>> (右移)

二进制右移运算符。 左操作数的值向右移动右操作数指定的位数。

(A >> 1) is 1.

示例

以下示例演示了 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

❮ CoffeeScript - 运算符和别名