Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ตัวดำเนินการบิตเวียร์ (Bitwise Operators) ใน C# คืออะไร

ตัวดำเนินการบิตเวียร์ทำงานกับบิต และดำเนินการทีละบิต

รายการตัวดำเนินการบิตเวียร์

ตัวดำเนินการคำอธิบายตัวอย่าง
&Binary AND: คัดลอกบิตไปยังผลลัพธ์ถ้ามีอยู่ในทั้งสองตัวถูกดำเนินการ(A & B) = 12 (0000 1100)
|Binary OR: คัดลอกบิตถ้ามีอยู่ในตัวถูกดำเนินการใดตัวหนึ่ง(A | B) = 61 (0011 1101)
^Binary XOR: คัดลอกบิตถ้าตั้งค่าในตัวถูกดำเนินการเพียงตัวเดียว(A ^ B) = 49 (0011 0001)
~Binary Ones Complement: ตัวดำเนินการเดี่ยว สลับบิต(~A) = 61 (1100 0011 ใน 2's complement)
<<Binary Left Shift: เลื่อนบิตไปทางซ้ายตามจำนวนที่ระบุA << 2 = 240 (1111 0000)
>>Binary Right Shift: เลื่อนบิตไปทางขวาตามจำนวนที่ระบุA >> 2 = 15 (0000 1111)

ตัวอย่าง

using System; 
namespace Demo { 
    class Program { 
        static void Main(string[] args) { 
            int a = 60; /* 60 = 0011 1100 */ 
            int b = 13; /* 13 = 0000 1101 */ 
            int c = 0; 
            c = a & b; Console.WriteLine("Value of c is {0}", c); 
            c = a | b; Console.WriteLine("Value of c is {0}", c); 
            c = a ^ b; Console.WriteLine("Value of c is {0}", c); 
            c = ~a; Console.WriteLine("Value of c is {0}", c); 
            c = a << 2; Console.WriteLine("Value of c is {0}", c); 
            c = a >> 2; Console.WriteLine("Value of c is {0}", c); 
            Console.ReadLine(); 
        } 
    } 
}

ผลลัพธ์

Value of c is 12 Value of c is 61 Value of c is 49 Value of c is -61 Value of c is 240 Value of c is 15