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

ตัวดำเนินการ Bitwise และ Bit Shift ใน C#

Bitwise operators ทำงานระดับบิต (Bit-by-bit) สมมติ A = 60 (0011 1100), B = 13 (0000 1101)

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

ตัวอย่างโค้ดเต็ม

using System;
namespace MyApplication {
    class Program {
        static void Main(string[] args) {
            int a = 60; // 0011 1100
            int b = 13; // 0000 1101
            int c = 0;
            c = a & b;  Console.WriteLine("Line 1 - AND: {0}", c);   // 12
            c = a | b;  Console.WriteLine("Line 2 - OR: {0}", c);    // 61
            c = a ^ b;  Console.WriteLine("Line 3 - XOR: {0}", c);   // 49
            c = ~a;     Console.WriteLine("Line 4 - NOT: {0}", c);   // -61
            c = a << 2; Console.WriteLine("Line 5 - Left Shift: {0}", c); // 240
            c = a >> 2; Console.WriteLine("Line 6 - Right Shift: {0}", c); // 15
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

Line 1 - AND: 12
Line 2 - OR: 61
Line 3 - XOR: 49
Line 4 - NOT: -61
Line 5 - Left Shift: 240
Line 6 - Right Shift: 15