Toán tử bitwise shift dịch chuyển các bit của số nguyên. Chỉ áp dụng cho kiểu nguyên có dấu hoặc không dấu.
Dịch trái (Left Shift <<)
x << n dịch bit của x sang trái n vị trí. Bit thấp được lấp 0. Tương đương x × 2ⁿ (nếu không overflow).
Ví dụ
#include <stdio.h>
int main() {
int y = 28; // nhị phân: 11100
for (int i = 0; i <= 3; ++i) {
printf("Left shift %d: %d (0x%X)\n", i, y << i, y << i);
}
return 0;
}
Kết quả
Left shift 0: 28 (0x1C) -> 11100 Left shift 1: 56 (0x38) -> 111000 Left shift 2: 112 (0x70) -> 1110000 Left shift 3: 224 (0xE0) -> 11100000
Dịch phải (Right Shift >>)
x >> n dịch bit sang phải n vị trí.
- Unsigned: Bit cao lấp 0 (logical shift)
- Signed: Bit cao lấp bit dấu (arithmetic shift) - bảo toàn dấu
Tương đương x / 2ⁿ (làm tròn về 0 hoặc -∞ tùy implementation).
Ví dụ
#include <stdio.h>
int main() {
int x = 10; // nhị phân: 1010
unsigned ux = 10;
printf("Signed:\n");
for (int i = 0; i < 3; i++) {
printf(" >> %d: %d\n", i, x >> i);
}
printf("Unsigned:\n");
for (int i = 0; i < 3; i++) {
printf(" >> %d: %u\n", i, ux >> i);
}
// Số âm
int neg = -10;
printf("Negative -10:\n");
for (int i = 0; i < 3; i++) {
printf(" >> %d: %d\n", i, neg >> i);
}
return 0;
}
Kết quả
Signed: >> 0: 10 >> 1: 5 >> 2: 2 Unsigned: >> 0: 10 >> 1: 5 >> 2: 2 Negative -10: >> 0: -10 >> 1: -5 >> 2: -3 (arithmetic shift: -10/4 = -2.5 -> -3)
Lưu ý quan trọng
- Undefined Behavior nếu: shift ≥ độ rộng bit (vd: int 32-bit shift 32), shift số âm
- Overflow signed left shift là UB
- Không dùng cho float/double
- Ưu tiên
unsignedcho thao tác bit
Ứng dụng thực tế
- Nhân/chia nhanh lũy thừa 2
- Bit masking, flag manipulation
- Serialization, network protocol
- Graphics, hash function, compression