게임 아이템 사용 여부 - 비트 플래그 
(옵션이 많을 때 유용하게 사용됨. 메모리, 속도 효율)

const unsigned char opt0 = 1 << 0;
const unsigned char opt1 = 1 << 1;
const unsigned char opt2 = 1 << 2;
const unsigned char opt3 = 1 << 3;

cout << bitset<8>(opt0) << endl;
cout << bitset<8>(opt1) << endl;
cout << bitset<8>(opt2) << endl;
cout << bitset<8>(opt3) << endl;

//아이템을 갖게 되는 이벤트 발생
unsigned char items_flag = 0;
cout << "No Item" << bitset<8>(items_flag) << endl;

//item0 on
items_flag |= opt0;
cout << "Item0 obtained" << bitset<8>(items_flag) << endl;

//item3 on
items_flag |= opt3// |= 비트켜기
cout << "Item3 obtained" << bitset<8>(items_flag) << endl;

//item3 lost
items_flag &= ~opt3; // &=, ~ 비트끄기
cout << "Item3 lost" << bitset<8>(items_flag) << endl;

//has item1 ?
if(items_flag & opt1) {cout <<"has item1' << endl;}
else{ cout << "not have item1" << endl;}

//has item0 ?
if(items_flag & opt0) {cout <<"has item0' << endl;}
else{ cout << "not have item0" << endl;}

<result>

0000 0001
0000 0010
0000 0100
0000 1000

no item 0000 0000
item0 obtained 0000 0001
item3 obtained 0000 1001
item3 lost 0000 0001
not have item1
has item0

색깔 값 추출하기 - 비트 마스크 사용 
(플래그의 비트를 조작하거나 검사할 때 사용)


unsigned int pixel_color = 0xDAA520;

cout << std::bitset<32>(pixel_color) << endl;

unsigned char green = (pixel_color & green_mask) >> 8;
//green값만 추출하기 위해서 오른쪽으로 8칸 미뤄준다. right shift 사용. 

unsigned char blue = pixel_color & blue_mask;

cout << "green" << bitset<8>(green) << " " << int(green) << endl;
cout << "blue" << bitset<8>(blue) << " " << int(blue) << endl;

<result>
0000 0000 1101 1010 1010 0101 0010 0000
green 1010 0101 165
blue 0010 0000 32


'programming > c++' 카테고리의 다른 글

*4.2 전역 변수, 정적 변수, 내부 연결, 외부 연결  (0) 2019.04.23
4.1 지역 변수, 범위, 지속기간  (0) 2019.04.23
3.8 비트단위 연산자  (0) 2019.04.22
3.7 이진수  (0) 2019.04.22
3.6 논리 연산자  (0) 2019.04.22
Posted by 도이(doi)
,