Typescript-bitwise-operators-examples
提供:Dev Guides
TypeScript-ビット演算子の例
変数A = 2およびB = 3を想定
Operator | Description | Example |
---|---|---|
& (Bitwise AND) | It performs a Boolean AND operation on each bit of its integer arguments. | (A & B) is 2 |
(BitWise OR) | It performs a Boolean OR operation on each bit of its integer arguments. | |
(A | B) is 3 | ^ (Bitwise XOR) |
It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR means that either operand one is true or operand two is true, but not both. | (A ^ B) is 1 | ~ (Bitwise Not) |
It is a unary operator and operates by reversing all the bits in the operand. | (~B) is -4 | << (Left Shift) |
It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2, shifting two positions is equivalent to multiplying by 4, and so on. | (A << 1) is 4 | >> (Right Shift) |
Binary Right Shift Operator. The left operand’s value is moved right by the number of bits specified by the right operand. | (A >> 1) is 1 | >>> (Right shift with Zero) |
例
var a:number = 2; //Bit presentation 10
var b:number = 3; //Bit presentation 11
var result;
result = (a & b);
console.log("(a & b) => ",result)
result = (a | b);
console.log("(a | b) => ",result)
result = (a ^ b);
console.log("(a ^ b) => ",result);
result = (~b);
console.log("(~b) => ",result);
result = (a << b);
console.log("(a << b) => ",result);
result = (a >> b);
console.log("(a >> b) => ",result);
コンパイル時に、次のJavaScriptコードが生成されます-
//Generated by typescript 1.8.10
var a = 2; //Bit presentation 10
var b = 3; //Bit presentation 11
var result;
result = (a & b);
console.log("(a & b) => ", result);
result = (a | b);
console.log("(a | b) => ", result);
result = (a ^ b);
console.log("(a ^ b) => ", result);
result = (~b);
console.log("(~b) => ", result);
result = (a << b);
console.log("(a << b) => ", result);
result = (a >> b);
console.log("(a >> b) => ", result);
上記のプログラムの出力は以下のとおりです-
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0