1. 비트플래그
- bitset
#include <iostream>
#include <bitset>
using namespace std;
int main() {
/*
bool item1_flag = false;
bool item2_flag = false;
bool item3_flag = false;
bool item4_flag = false;
*/
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;
items_flag |= opt0;
cout << "Item 0 obtained " << bitset<8>(items_flag) << endl;
items_flag |= opt3;
cout << "Item 3 obtained " << bitset<8>(items_flag) << endl;
items_flag &= ~opt3;
cout << "Item 3 lost " << bitset<8>(items_flag) << endl;
if (items_flag & opt1) {
cout << "Has item1" << endl;
}
else { cout << "Not have item1" << endl; }
items_flag |= (opt2 | opt3);
cout << "Item 2,3 obtained " << bitset<8>(items_flag) << endl;
if ((items_flag & opt2) && !(items_flag & opt1)) {
items_flag ^= opt2;
items_flag ^= opt1;
}
return 0;
}
2. 비트마스크
#include <iostream>
#include <bitset>
using namespace std;
int main() {
const unsigned int red_mask = 0xFF0000;
const unsigned int green_mask = 0x00FF00;
const unsigned int blue_mask = 0x0000FF;
unsigned int pixel_color = 0xDAA520;
unsigned char red, green, blue;
cout << bitset<32>(pixel_color) << endl;
red = (pixel_color & red_mask)>>16;
cout << "red " << bitset<8>(red) << " " << int(red) << endl;
green = (pixel_color & green_mask)>>8;
cout << "green " << bitset<8>(green) << " " << int(green) << endl;
blue = pixel_color & blue_mask;
cout << "blue " << bitset<8>(blue) << " " << int(blue) << endl;
return 0;
}
'코딩 > C++' 카테고리의 다른 글
namespace, auto, trailing, 암시적 형변환, 명시적 형변환 (0) | 2024.02.21 |
---|---|
전역변수, static 변수, 내부 연결, 외부 연결 (0) | 2024.02.19 |
const (0) | 2024.02.17 |
namespace (0) | 2024.02.16 |
헤더파일과 헤더 가드 (0) | 2024.02.16 |