본문 바로가기

C_study

[C] 코딩도장 56 : 구조체 비트 필드 사용하기

비트 필드를 사용하면 구조체 멤버를 비트 단위로 저장할 수 있다.

#include <stdio.h>

struct cafe {
	unsigned int a : 1; // 자료형 멤버변수명 : 비트 크기 형태로 정의한다 
	unsigned int b : 3;
	unsigned int c : 7;
};

int main() 
{
	struct cafe cafe1;

	cafe1.a = 1; // 0000 0001 , 1비트 크기로 저장되므로 1이 저장됨
	cafe1.b = 15; // 0000 1111 , 3비트 크기로 저장되므로 111이 저장됨
	cafe1.c = 255; // 1111 1111 , 7비트 크기로 저장되므로 111 1111이 저장됨

	printf("%u\n", cafe1.a); // 1
	printf("%u\n", cafe1.b); // 7
	printf("%u\n", cafe1.c); // 127
	
	return 0;
}

정의된 비트크기보다 큰 비트는 나머지가 버려진다. 

비트 필드의 값을 한번에 저장할 때 공용체를 사용해서 저장할 수 있다.

 

심사문제 56.6 풀이

#include <stdio.h>
 
struct Flags {
	unsigned int a : 4; // 15가 나와야 하므로 4
	unsigned int b : 7; // 127가 나와야 하므로 7
	unsigned int c : 3; // 7이 나와야 하므로 3
};

int main()
{
    struct Flags f1;

    f1.a = 0xffffffff; 
    f1.b = 0xffffffff;
    f1.c = 0xffffffff;

    printf("%u %u %u\n", f1.a, f1.b, f1.c); // 15, 127, 7

    return 0;
}

심사문제 56.7 풀이

#include <stdio.h>

struct Flags {
    union {
        struct {
            unsigned short a : 3; 
	    unsigned short b : 4;
	    unsigned short c : 7;
	    unsigned short d : 2;
        };
        unsigned short e;  
    };
};
 
int main()
{
    struct Flags f1 = { 0, };
 
    f1.a = 4; // 2진수로 나타내면 100
    f1.b = 8; // 2진수로 나타내면 1000
    f1.c = 64; // 2진수로 나타내면 100 0000 
    f1.d = 3; // 2진수로 나타내면 11

    printf("%u\n", f1.e); // 57412가 나와야 함, 2진수로는 1110 0000 0100 0100

    return 0;
}