Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Bit Fields ในภาษา C


ในส่วนนี้เราจะดูว่า bit fields ใน C คืออะไร

สมมติโปรแกรม C มีตัวแปร TRUE/FALSE หลายตัว จัดกลุ่มใน structure ชื่อ status:

struct {    unsigned int widthValidated;    unsigned int heightValidated; } status;

โครงสร้างนี้ต้องการ 8 bits แต่จริงๆ เก็บแค่ 0 หรือ 1 ในแต่ละตัวแปร C มีวิธีประหยัดหน่วยความดีกว่า

ถ้าใช้ตัวแปรแบบนี้ใน structure สามารถกำหนดความกว้างของตัวแปรได้ บอก compiler ว่าจะใช้ bits เท่านั้น เช่น:

struct {    unsigned int widthValidated : 1;    unsigned int heightValidated : 1; } status;

โครงสร้างนี้ใช้ 4 bits สำหรับ status แต่เก็บค่าได้แค่ 2 bits หากใช้ถึง 32 ตัวแปรแต่ละตัว 1 bit ก็ยังใช้ 4 bits แต่ถ้า 33 ตัว จะ allocate memory slot ถัดไป ใช้ 8 bits

ตัวอย่างโค้ด

#include <stdio.h> #include <string.h> /* define simple structure */ struct {    unsigned int widthValidated;    unsigned int heightValidated; } status1; /* define a structure with bit fields */ struct {    unsigned int widthValidated : 1;    unsigned int heightValidated : 1; } status2; int main( ) {    printf( "Memory size occupied by status1 : %d\n", sizeof(status1));    printf( "Memory size occupied by status2 : %d\n", sizeof(status2));    return 0; }

ผลลัพธ์

Memory size occupied by status1 : 8 Memory size occupied by status2 : 4

Bit Field Declaration:

การประกาศ bit-field ใน structure:

struct {    type [member_name] : width ; };
ElementsDescription
typeinteger type (int, signed int, unsigned int) กำหนดการ interpret ค่า
member_nameชื่อของ bit-field
widthจำนวน bits ต้อง ≤ bit width ของ type ที่ระบุ

Bit field สามารถเก็บมากกว่า 1 bit ได้ เช่น ต้องการเก็บค่า 0-7 ใช้ width 3 bits:

struct {    unsigned int age : 3; } Age;

Compiler จะอนุญาตแค่ 3 bits หากพยายามเก็บเกินกว่านั้นจะไม่ได้ ตัวอย่าง:

ตัวอย่างโค้ด

#include <stdio.h> #include <string.h> struct {    unsigned int age : 3; } Age; int main( ) {    Age.age = 4;    printf( "Sizeof( Age ) : %d\n", sizeof(Age) );    printf( "Age.age : %d\n", Age.age );    Age.age = 7;    printf( "Age.age : %d\n", Age.age );    Age.age = 8;    printf( "Age.age : %d\n", Age.age );    return 0; }

ผลลัพธ์

Sizeof( Age ) : 4 Age.age : 4 Age.age : 7 Age.age : 0