C#의 BitConverter.ToUInt64() 메서드는 바이트 배열 내 지정된 위치부터 8바이트를 읽어들여, 이를 64비트 부호 없는 정수(ulong)로 변환한 값을 반환합니다. 네트워크 데이터 파싱, 파일 형식 분석 등 바이트 단위 데이터를 다룰 때 매우 유용하게 활용됩니다.
구문
public static ulong ToUInt64(byte[] val, int startIndex);
매개변수
val: 변환 대상이 되는 바이트 배열입니다.
startIndex: 변환을 시작할 배열 내 위치(인덱스)입니다.
배열의 남은 길이가 8바이트보다 작으면 ArgumentOutOfRangeException이, 배열이 null이면 ArgumentNullException이 발생하므로 주의해야 합니다.
예제 1: 기본 사용법
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 - 7; i = i + 8) {
ulong res = BitConverter.ToUInt64(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 = 1083970061066240256
예제 2: 여러 위치에서 변환하기
배열 길이가 충분히 길다면 반복문을 통해 여러 위치에서 연속적으로 8바이트씩 변환할 수 있습니다.
using System;
public class Demo {
public static void Main() {
byte[] arr = { 0, 0, 1, 3, 5, 7, 9, 11, 15, 0, 1, 6, 8, 10, 20, 25, 36, 34 };
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 - 7; i = i + 8) {
ulong res = BitConverter.ToUInt64(arr, i);
Console.WriteLine("\nValue = " + arr[i]);
Console.WriteLine("Result = " + res);
}
}
}실행 결과
Byte Array... 0 0 1 3 5 7 9 11 15 0 1 6 8 10 20 25 36 34 Byte Array (String representation) = 00-00-01-03-05-07-09-0B-0F-00-01-06-08-0A-14-19-24-22 Value = 0 Result = 1083970061066240256 Value = 0 Result = 2601132293100011776
정리
BitConverter.ToUInt64()는 바이트 배열에서 8바이트를 지정된 인덱스부터 읽어 ulong 값으로 변환하는 간단하면서도 강력한 메서드입니다. 반복문과 조합하면 대용량 바이트 스트림에서도 손쉽게 64비트 정수 데이터를 추출할 수 있습니다.