Language/C
[따배씨] 15.11 비트필드의 패딩
migrationArc
2021. 7. 29. 22:16
따배씨 - 따라하며 배우는 C언어
15강 비트 다루기
15.11 비트필드 Bits-Fields 의 패딩 Padding
#include <stdio.h>
#include <limits.h> // CHAR_BIT
#include <stdbool.h>
#include <string.h>
void char_to_binary (unsigned char uc)
{
const int bits = CHAR_BIT * sizeof(unsigned char);
for (int i = bits - 1; i >= 0; i--)
{
printf("%d", (uc >> i) & 1);
}
}
void print_binary(char* data, int bytes)
{
for (int i = 0; i < bytes; i++)
{
char_to_binary(data[bytes - 1 - i]);
printf("\n");
}
}
int main()
{
struct{
bool option1 : 7;
bool option2 : 2;
} bbf;
// Error
// x-code 에서는 compiler 가 bool 에 1bit 초과한 bit 를 할당하지 못하게 함
printf("%zu bytes\n", sizeof(bbf));
// 0 bytes
struct {
unsigned short option1 : 8;
unsigned short option2 : 7;
//unsigned short : 0;
unsigned short option3 : 1;
} usbf;
printf("%zu bytes\n", sizeof(usbf));
// 2 bytes
struct {
unsigned int option1 : 1;
unsigned int option2 : 1;
} uibf;
printf("%zu bytes\n", sizeof(uibf));
// 4 bytes
return 0;
}
- 32bit CPU는 메모리에서 값을 읽어 올 때 한번에 4byte(32bit), 64bit CPU는 한번에 8byte (64bit) 를 읽음 - word 단위
- 구조체에 접근 시 메모리를 읽는 횟수 (효율성) 을 높이기 위하여, 메모리 공간을 낭비하더라도 성능을 높이기 위해 padding-bit 를 사용
이 글의 모든 사진과 내용의 출처는 홍정모 교수님께 있음을 알려드립니다.
http://blog.naver.com/atelierjpro
실리콘 밸리의 프로그래머 : 네이버 블로그
안녕하세요! 홍정모 블로그에 오신 것을 환영합니다. 주로 프로그래밍 관련 메모 용도로 사용합니다. 강의 수강하시는 분들은 홍정모 연구소 카페로 오세요.
blog.naver.com
http://www.inflearn.com/course/following-c
홍정모의 따라하며 배우는 C언어 - 인프런 | 강의
'따배씨++'의 성원에 힘입어 새롭게 개발된 C 언어로 시작하는 프로그래밍 입문 강의입니다. '따배씨'와 함께 프로그래밍 인생을 업그레이드 해보세요., 따라하며 배우는 C언어 '따배씨++'의 성원
www.inflearn.com