Show 例子 6

优质
小牛编辑
119浏览
2023-12-01

CoffeeScript支持以下按位运算符。 假设变量A保持2而变量B保持3 ,则 -

Sr.No运算符和描述
1

& (Bitwise AND)

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

(A&B)是2。
2

| (BitWise OR)

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

(A | B)是3。
3

^ (Bitwise XOR)

它对其整数参数的每个位执行布尔异或运算。 异或表示操作数1为真或操作数2为真,但不是两者。

(A ^ B)是1。
4

~ (Bitwise Not)

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

(~B) is -4.
5

《《 (Left Shift)

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

(A << 1)是4。
6

》》 (Right Shift)

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

(A >> 1)是1。

例子 (Example)

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

打开command prompt并编译.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);

现在,再次打开command prompt并运行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