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

ตัวดำเนินการ Left Shift และ Right Shift ใน C/C++

Left Shift (<<)

เลื่อนบิตของตัวถูกดำเนินการซ้าย ตามจำนวนบิตที่ระบุ

ตัวอย่าง

#include <stdio.h>

int main() {
    int y = 28; // 11100 ใน binary
    for (int i = 0; i <= 3; ++i)
        printf("Left shift by %d: %d\n", i, y << i);
    return 0;
}

ผลลัพธ์

Left shift by 0: 28
Left shift by 1: 56
Left shift by 2: 112
Left shift by 3: 224

Right Shift (>>)

เลื่อนบิตของตัวถูกดำเนินการขวา ตามจำนวนบิตที่ระบุ

ตัวอย่าง

#include <stdio.h>

int main() {
    int x = 10; // 1010 ใน binary
    for (int i = 0; i < 2; i++)
        printf("Right shift by %d: %d\n", i, x >> i);
    return 0;
}

ผลลัพธ์

Right shift by 0: 10
Right shift by 1: 5

หมายเหตุ

  • Left Shift 1 บิต = คูณ 2
  • Right Shift 1 บิต = หาร 2 (ปัดลง)
  • ใช้กับ Signed Integer ต้องระวัง Sign Bit