1. 기본( &(검사), |(추가), &= ~(삭제) )
#include <stdio.h>
#define KAL 1
#define BANG 2
void display( int item )
{
printf("\n\n소유 아이템\n");
printf("----------------\n");
if( item & KAL ) // 0011 & 0001
printf("칼 소유\n");
if( item & BANG ) // 0011 & 0010
printf("갑옷 소유\n");
printf("----------------\n");
}
int main()
{
int item=0;
display( item );
item |= KAL; // 0000 | 0001 => 0001
display(item);
item |= BANG; // 0001 | 0010 => 0011
display(item);
item &= ~KAL; // 0011 & 1110 => 0010
display(item);
return 0;
}
2. 배열을 사용한 비트 플래그
#include <stdio.h>
#define KAL 10
#define BANG 50 #define MAX 1024 #define SIZE(a) (sizeof(a)*8)
void display( int *item )
{
int i;
printf("\n\n소유 아이템\n");
printf("----------------\n");
for( i=0; i<2* SIZE(*item); i++ )
{
if( item[i/SIZE(*item)] & ( 1<<(i%SIZE(*item)) ) )
printf("item : %2d\n", i );
}
printf("----------------\n");
}
int main()
{
int item[MAX/32]={0,};
display( item );
item[KAL/SIZE(*item)] |= 1<<( KAL % SIZE(*item) ); // 0000000000000000 | 10000000000 => 10000000000
display(item);
item[BANG/SIZE(*item)] |= 1<<( BANG % SIZE(*item));
// 000000000000000000000
//| 001000000000000000000
// 001000000000000000000
// [0] => 00000000000000000000010000000000
// [1] => 00000000000001000000000000000000
display(item);
item[KAL/SIZE(*item)] &= ~(1<<( KAL % SIZE(*item) ));
display(item);
return 0;
}
3. 매크로를 이용한 비트 플래그 연산(
#include <stdio.h>
#define NFDBITS (8 * sizeof(unsigned long))
#define FD_SETSIZE 1024
#define FDSET_LONGS ( FD_SETSIZE/NFDBITS )
#define FDELT(d) ((d) / NFDBITS)
#define FDMASK(d) (1UL << ((d) % NFDBITS))
#define FD_SET(d, set) ((set)->fds_bits[FDELT(d)] |= FDMASK(d))
#define FD_CLR(d, set) ((set)->fds_bits[FDELT(d)] &= ~FDMASK(d))
#define FD_ISSET(d, set) ((set)->fds_bits[FDELT(d)] & FDMASK(d))
#define FD_ZERO(fdsetp) (memset (fdsetp, 0, sizeof(*(fd_set *)fdsetp)))
typedef struct {
unsigned long fds_bits [FDSET_LONGS];
} fd_set;
int main()
{
fd_set read_fds;
FD_ZERO( &read_fds );
FD_SET( 4, &read_fds );
FD_ISSET( 4, &read_fds );
FD_CLR( 4, &read_fds );
return 0;
}