본문 바로가기
공부,일/c언어

비트필드

by fromnothing1 2021. 6. 3.

비트필드

bit 단위로 구조체의 멤버를 제어할 수 있는 특수한 형태의 구조체 

 

비트 필드는 data type 으로 int 와 unsigned 만 사용할 수 있다.

#include<stdio.h>

int main()
{
	// 보통 하나의 bit 필드는 2byte 크기이다. 
	struct COM_PORT {
		unsigned baud : 3;
		unsigned parity : 2;
		unsigned stop : 1;
		unsigned data : 2;
	}ps;

	ps.baud = 7;
	ps.parity = 3;
	ps.stop = 1;
	ps.data = 3;

	printf("%p\n", &ps);

	printf("ps.baud : %d\n", ps.baud); // printf 하면 보여주네 ? 
	printf("ps.parity : %d\n", ps.parity);
	printf("ps.stop : %d\n", ps.stop);
	printf("ps.data : %d\n", ps.data);

	// bit fled 를 비워두고 싶을때 선언 방식

	struct COM_PORT2 {
		unsigned baud : 3;
		unsigned : 2;     // 2bit 건너 뛰고 저장 된다. 
		unsigned stop : 1;
		unsigned data : 2;
	}ps2;


	// 16 bit 넘을 때 16bit 공간을 할당하라는 코드
	struct COM_PORT3{

		unsigned baud : 3; // 상위 16 bit 

		unsigned : 0;		//다음 16 bit 확보하라는 의미 

		unsigned stop : 1; // 하위 16bit
		unsigned data : 2;
	}ps3;


	return 0;
}

'공부,일 > c언어' 카테고리의 다른 글

구조체의 padding  (0) 2021.06.04
공용체  (0) 2021.06.04
구조체  (0) 2021.06.03
함수포인터  (0) 2021.06.02
sizeof 와 포인터 & 배열의 data type  (0) 2021.06.01

댓글