C#에서 비트 연산은 성능이 중요한 작업 중 하나입니다. .NET 5부터는 System.Numerics.BitOperations 클래스를 통해 여러 비트 연산을 효율적으로 수행할 수 있습니다.
1. BitOperations 주요 메서드
BitOperations는 빠른 하드웨어 명령어를 사용해 아래와 같은 작업을 제공합니다:
PopCount: 1 비트 개수 세기LeadingZeroCount: 선행 0 개수TrailingZeroCount: 후행 0 개수RotateLeft,RotateRight: 비트 회전
2. 사용 예시
using System;
using System.Numerics;
class Program
{
static void Main()
{
uint value = 0b_0001_1010_1000_1111;
int popCount = BitOperations.PopCount(value); // 1 비트 개수
int leadingZeros = BitOperations.LeadingZeroCount(value); // 선행 0 개수
int trailingZeros = BitOperations.TrailingZeroCount(value);// 후행 0 개수
uint rotatedLeft = BitOperations.RotateLeft(value, 3); // 3비트 왼쪽 회전
Console.WriteLine($"PopCount: {popCount}");
Console.WriteLine($"LeadingZeroCount: {leadingZeros}");
Console.WriteLine($"TrailingZeroCount: {trailingZeros}");
Console.WriteLine(Convert.ToString(rotatedLeft, toBase: 2));
}
}
3. 성능 최적화 팁
전통적인 반복문을 이용한 비트 카운팅보다 BitOperations 메서드는 CPU 명령어를 직접 활용해 훨씬 빠릅니다. 특히 대규모 데이터에서 성능 차이가 큽니다.
따라서 비트 연산이 잦은 로직에서는 BitOperations 사용을 적극 권장합니다.
간단하지만 성능에 큰 도움을 주는 BitOperations로 코드 최적화를 시작해보세요!
'C#' 카테고리의 다른 글
| C# TimeSpan과 Stopwatch로 성능 측정 및 시간 연산 (0) | 2026.05.16 |
|---|---|
| C# DateTime과 DateTimeOffset 차이 이해하기 (0) | 2026.05.16 |
| C# Local Function을 활용한 코드 가독성 개선 (0) | 2026.05.15 |
| C# System.Threading.Channels로 비동기 데이터 파이프라인 구성 (0) | 2026.05.14 |
| C# Polyglot 애플리케이션: IronPython과의 상호운용 (0) | 2026.05.14 |