C#의 BitConverter.ToUInt32() 메서드는 바이트 배열 내 지정된 위치에서 시작하는 4바이트를 읽어, 이를 32비트 부호 없는 정수(uint)로 변환하여 반환합니다. 네트워크 데이터 처리, 파일 형식 파싱, 바이너리 데이터 분석 등에서 자주 활용되는 핵심 메서드입니다.
문법(Syntax)
public static uint ToUInt32(byte[] val, int begnIndex);
매개변수 설명
- val: 변환할 대상이 되는 바이트 배열입니다.
- begnIndex: 변환을 시작할 배열 내 위치(인덱스)입니다.
이 메서드는 시작 인덱스부터 4바이트를 읽어 변환하므로, 배열의 길이가 시작 인덱스 + 4보다 작으면 ArgumentException이 발생할 수 있습니다.
예제 1
using System;
public class Demo {
public static void Main() {
byte[] arr = { 0, 3, 5, 10, 15, 2 };
int count = arr.Length;
Console.Write("Byte Array... ");
for (int i = 0; i < count; i++) {
Console.Write("\n" + arr[i]);
}
Console.WriteLine("\n\nByte Array (String representation) = {0} ",
BitConverter.ToString(arr));
for (int i = 1; i < arr.Length - 1; i = i + 4) {
uint res = BitConverter.ToUInt32(arr, i);
Console.WriteLine("\nValue = " + arr[i]);
Console.WriteLine("Result = " + res);
}
}
}출력 결과
Byte Array... 0 3 5 10 15 2 Byte Array (String representation) = 00-03-05-0A-0F-02 Value = 3 Result = 252314883
위 예제에서는 인덱스 1부터 4바이트(3, 5, 10, 15)를 읽어 하나의 uint 값으로 변환했습니다. C#은 기본적으로 리틀 엔디안(little-endian) 방식을 사용하기 때문에, 낮은 주소의 바이트가 정수의 하위 바이트에 배치됩니다.
예제 2
using System;
public class Demo {
public static void Main() {
byte[] arr = { 0, 0, 1, 3, 5, 7, 9, 11, 15 };
int count = arr.Length;
Console.Write("Byte Array... ");
for (int i = 0; i < count; i++) {
Console.Write("\n" + arr[i]);
}
Console.WriteLine("\n\nByte Array (String representation) = {0} ",
BitConverter.ToString(arr));
for (int i = 1; i < arr.Length - 1; i = i + 4) {
uint res = BitConverter.ToUInt32(arr, i);
Console.WriteLine("\nValue = " + arr[i]);
Console.WriteLine("Result = " + res);
}
}
}출력 결과
Byte Array... 0 0 1 3 5 7 9 11 15 Byte Array (String representation) = 00-00-01-03-05-07-09-0B-0F Value = 0 Result = 84082944 Value = 7 Result = 252381447
두 번째 예제에서는 루프가 인덱스 1과 인덱스 5 두 곳에서 각각 4바이트씩 읽어 두 개의 서로 다른 uint 값을 반환한 것을 확인할 수 있습니다.
정리
BitConverter.ToUInt32()는 바이트 배열의 특정 위치에서 4바이트를 추출해 32비트 부호 없는 정수로 변환하는 간단하고 효율적인 방법입니다. 단, 변환 시 배열 범위를 벗어나지 않도록 인덱스를 신중하게 관리해야 하며, 필요에 따라 BitConverter.ToInt32()(부호 있는 정수)나 BinaryPrimitives.ReadUInt32LittleEndian() 같은 대안도 고려해 볼 수 있습니다.