본문 바로가기
C Programming

[C] 공용체를 활용한 비트 연산

by TYB 2023. 10. 14.
반응형
#include <stdio.h>
#pragma warning(disable:4996)
/*
[입력]
●비트연산자를수행할두개의입력
[출력]
●입력받은두정수x, y에서다음비트연산의결과를출력
■x, y, x & y, x | y, x ^ y, x >> y, x << y, ~x, ~y, ~x + 1. ~y + 1 등을출력
■이진수는다음과같이4자리출력후빈공간출력

32bit=4byte int
비트연산을수행할두개의정수를입력하세요. >> 387 5
387:                     0000 0000 0000 0000 0000 0001 1000 0011
5:                          0000 0000 0000 0000 0000 0000 0000 0101
387 & 5 = 1:         0000 0000 0000 0000 0000 0000 0000 0001
387 | 5 = 391:       0000 0000 0000 0000 0000 0001 1000 0111
387 ^ 5 = 390:      0000 0000 0000 0000 0000 0001 1000 0110
387 >> 5 = 12:      0000 0000 0000 0000 0000 0000 0000 1100
387 << 5 = 12384:  0000 0000 0000 0000 0011 0000 0110 0000
~387 = -388:       1111 1111 1111 1111 1111 1110 0111 1100
~ 5 = -6:          1111 1111 1111 1111 1111 1111 1111 1010


*/
typedef union u{
    unsigned int B4;

    struct {
        unsigned int b0 : 1, b1 : 1, b2 : 1, b3 : 1, b4 : 1, b5 : 1, b6 : 1, b7 : 1, b8 : 1, b9 : 1, b10 : 1, b11 : 1,
            b12 : 1, b13 : 1, b14 : 1, b15 : 1, b16 : 1, b17 : 1, b18 : 1, b19 : 1, b20 : 1, b21 : 1, b22 : 1, b23 : 1,
            b24 : 1, b25 : 1, b26 : 1, b27 : 1, b28 : 1, b29 : 1, b30 : 1, b31 : 1;
    }s;

}u1

void print_int_to_bit(u1 *input, int *res, char ment[10][6])
{
    
    int i,j;
    for (i = 0; i < 9; i++) {
        (input+i)->B4 = *(res+i);
        printf("%s\t", *(ment + i));
        printf("%d%d%d%d %d%d%d%d %d%d%d%d %d%d%d%d %d%d%d%d %d%d%d%d %d%d%d%d %d%d%d%d \n", (input + i)->s.b31, (input + i)->s.b30, (input + i)->s.b29, (input + i)->s.b28,
            (input + i)->s.b27, (input + i)->s.b26, (input + i)->s.b25, (input + i)->s.b24, (input + i)->s.b23, (input + i)->s.b22, (input + i)->s.b21, (input + i)->s.b20, 
            (input + i)->s.b19, (input + i)->s.b18, (input + i)->s.b17, (input + i)->s.b16, (input + i)->s.b15, (input + i)->s.b14, (input + i)->s.b13, (input + i)->s.b12,
            (input + i)->s.b11, (input + i)->s.b10, (input + i)->s.b9, (input + i)->s.b8, (input + i)->s.b7, (input + i)->s.b6, (input + i)->s.b5, (input + i)->s.b4,
            (input + i)->s.b3, (input + i)->s.b2, (input + i)->s.b1, (input + i)->s.b0 );
    }


}

int main(void)
{
    unsigned bb[32];
    u1 BT[10]; 

    //연산별프린트용
    char ment[10][6] = {
        "a=",
        "b=",
        "a&b=",
        "a|b=",
        "a^b",
        "a>>b",
        "a<<b",
        "~a",
        "~b",


    };
    unsigned int a = 0, b = 0;
    int res[10] = { 0 };
    //int bit[10][32];
    int i, j;
    printf("enter two num: ");
    scanf("%d %d", &a, &b);

    res[0] = a;
    res[1] = b;
    res[2] = a & b;
    res[3] = a | b;
    res[4] = a ^ b;
    res[5] = a >> b;
    res[6] = a << b;
    res[7] = ~a;
    res[8] = ~b;
    print_int_to_bit(BT, res, ment);




    return 0;
}
반응형