Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Xoay bit (Bit Rotation) trong C


Xoay bit trái/phải: bit bị đẩy ra một đầu sẽ quay về đầu kia.

Xoay trái (Left Rotation)

Bit MSB dịch ra → thành LSB mới.

#include <stdio.h>
#include <stdlib.h>
int main() {
    int num, rot, msb, size = sizeof(int)*8;
    printf("Nhap so: "); scanf("%d", &num);
    printf("Nhap so lan xoay: "); scanf("%d", &rot);
    rot %= size;
    while (rot--) {
        msb = (num >> (size-1)) & 1; // lay MSB
        num = (num << 1) | msb;      // dich trai, them MSB vao LSB
    }
    printf("Sau xoay trai: %d", num);
    return 0;
}

Kết quả

Nhap so: 12 (1100)
Nhap so lan xoay: 2
Sau xoay trai: 48 (110000)

Xoay phải (Right Rotation)

Bit LSB dịch ra → thành MSB mới.

#include <stdio.h>
#include <stdlib.h>
int main() {
    int num, rot, lsb, size = sizeof(int)*8;
    printf("Nhap so: "); scanf("%d", &num);
    printf("Nhap so lan xoay: "); scanf("%d", &rot);
    rot %= size;
    while (rot--) {
        lsb = num & 1;                 // lay LSB
        num = (num >> 1) | (lsb << (size-1)); // dich phai, them LSB vao MSB
    }
    printf("Sau xoay phai: %d", num);
    return 0;
}

Kết quả

Nhap so: 18 (10010)
Nhap so lan xoay: 2
Sau xoay phai: 4 (00100)