본문 바로가기
C++ 200제/코딩 IT 정보

C# 비트연산 - 플래그 응용 (bit flag enum 연산자 예제)

by vicddory 2017. 7. 27.

C# 비트연산 - 플래그 응용 (bit flag enum 연산자 예제)


enum 플래그 속성은 대개 비트 연산자를 다룰 때 사용합니다.


예를 들면 이렇죠.


1
myProperties.AllowedColors = MyColor.Red | MyColor.Green | MyColor.Blue;
cs


플래그 자체를 더 효율적으로 표현하려면 .ToString()를 사용하는 것이 좋습니다.


1
2
3
4
5
6
7
8
9
enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
[Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }
 
...
 
var str1 = (Suits.Spades | Suits.Diamonds).ToString();
// "5"
var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString();
// "Spades, Diamonds"
cs


또한, enum에선 자동으로 2의 배수로 값이 증가하지 않습니다. 기본적으로 0에서 시작합니다.

잘못된 선언:


1
2
3
4
5
6
7
8
[Flags]
public enum MyColors
{
    Yellow,
    Green,
    Red,
    Blue
}
cs


이 경우 값은 Yellow = 0, Green = 1, Red = 2, Blue = 3이 되니 플래그론 소용이 없죠.


올바른 선언 방법:


1
2
3
4
5
6
7
8
[Flags]
public enum MyColors
{
    Yellow = 1,
    Green = 2,
    Red = 4,
    Blue = 8
}
cs


c# 비트연산[C# 비트연산 - 플래그 응용 (bit flag enum)]


또, 플래그 속성에서 고유 값을 검색하려면 아래처럼 구성합니다.


1
2
3
4
if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow)
{
    // Yellow has been set...
}
cs


1
2
3
4
if((myProperties.AllowedColors & MyColor.Green) == MyColor.Green)
{
    // Green has been set...
}
cs

닷넷 4.0 이상에선:


1
2
3
4
if (myProperties.AllowedColors.HasFlag(MyColor.Yellow))
{
    // Yellow has been set...
}
cs


추가로, 아래처럼 2의 제곱 값을 설정해 8bit 데이터로 이용할 수도 있습니다. (0과 1을 사용해 8bit 1바이트로 응용)


1
2
3
4
 Yellow: 00000001
 Green:  00000010
 Red:    00000100
 Blue:   00001000
cs


c# 플래그[C# 비트연산 - 플래그 응용 (bit flag enum)]


비슷하게 AllowedColors 속성을 Red, Green, Blue로 설정하면 AllowedColors는 다음과 같습니다.


1
myProperties.AllowedColors: 00001110
cs


값을 가져올 땐 비트값으로 and 연산합니다.


1
2
3
4
5
6
7
myProperties.AllowedColors: 00001110
             MyColor.Green: 00000010
             -----------------------
                            00000010
// Hey, this is the same as MyColor.Green!
 
None = 0
cs


그리고 enumeration에서 0을 사용하려면 MSDN의 내용을 따라 :


1
2
3
4
5
6
[Flags]
public enum MyColors
{
    None = 0,
    ....
}
cs


이렇게 사용하죠.


값이 0인 플래그는 None으로 사용하세요. 결과가 항상 0이라 AND 연산 등에서 비트 설정 여부를 확인할 수 있도록 돕습니다.


C# 비트연산 - 플래그 응용 (bit flag enum 연산자 예제)

댓글