C – 구조체 비트 필드(struct bit field)

By | 2022년 2월 8일
Table of Contents

C – 구조체 비트 필드(struct bit field)

참조

. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .

기본 문법

정수형에는 char, short, int, long 이 올 수 있다.

struct 구조체명 {
    unsigned 정수형 멤버필드1 : 비트수;
    unsigned 정수형 멤버필드2 : 비트수;
    ...
};

// 예제
struct file_access {
    unsigned short other     : 3; // rwx
    unsigned short group     : 3; // rwx
    unsigned short owner     : 3; // rwx
    unsigned short type      : 3;
    unsigned short egroup    : 1;
    unsigned short euser     : 1;
};

구조체의 크기

구조체의 크기는 가장 큰 필드 타입을 따라간다.

가장 큰 필드 타입보다 더 많은 데이타가 있는 경우,
구조체의 크기가 모든 데이타를 담을 수 있을만큼 N 배 커진다.

두번째 구조체 option_large3 + 6 = 9 비트의 크기이므로,
char(8bit) * 2 만큼 커진다.

struct option {
    unsigned char  flag1 : 1;
    unsigned short flag2 : 1;
};

struct option_large {
    unsigned char opt1 : 3;
    unsigned char opt2 : 6;
};

저장 형태

실제 메모리에 저장되는 방식은 다음과 같다.(gcc 기준)

단, 실제 저장방식은 컴파일러 종속적(컴파일러 맘대로)이기 때문에,
실제로 어떻게 저장되는지는 확인해 보아야 한다.

#include <stdio.h>
#include <string.h>

typedef struct _bitfield {
    unsigned char b7 : 1;
    unsigned char b6 : 1;
    unsigned char b5 : 1;
    unsigned char b4 : 1;
    unsigned char b3 : 1;
    unsigned char b2 : 1;
    unsigned char b1 : 1;
    unsigned char b0 : 1;
} bitfield;

void ten_to_two(unsigned char n) {
    unsigned char a = 0x80; // 1000 0000
    for (int i = 0; i < 8; i++) {
        if ((a & n) == a)
            printf("1");
        else
            printf("0");
        a >>= 1;
    }
}

int main() {
    // ASCII : A, 10진수 : 65, 2진수 : 01000001
    char ch = 'A';
    char ch2;

    printf("char : %c, 10 진수 : %d,  2진수 : ", ch, ch);
    ten_to_two(ch);
    printf("\n");

    bitfield b;
    b.b0 = 0;
    b.b1 = 1;
    b.b2 = 0;
    b.b3 = 0;
    b.b4 = 0;
    b.b5 = 0;
    b.b6 = 0;
    b.b7 = 1;

    memcpy(&ch2, &b, sizeof(ch2));
    ten_to_two(ch2);
    printf("\n");
}

답글 남기기