C#의 BitConverter.ToUInt16() 메서드는 바이트 배열 내 지정된 위치에서 연속된 두 개의 바이트를 읽어 16비트 부호 없는 정수(ushort)로 변환해 반환합니다. 네트워크 패킷 파싱, 파일 헤더 분석, 임베디드 장비와의 통신 등 원시(raw) 바이트 데이터를 직접 다뤄야 할 때 매우 유용하게 활용됩니다.
구문
public static ushort ToUInt16 (byte[] val, int startIndex);
각 매개변수의 의미는 다음과 같습니다.
- val : 변환 대상이 되는 바이트 배열
- startIndex : 변환을 시작할 배열 내 위치(인덱스)
이 메서드는 지정된 인덱스부터 두 바이트를 읽어 값을 만들며, Windows 환경에서 일반적으로 사용되는 리틀 엔디안(little-endian) 방식에 따라 첫 번째 바이트는 하위 바이트(low byte), 두 번째 바이트는 상위 바이트(high byte)로 해석됩니다.
예제 1
using System;
public class Demo {
public static void Main() {
byte[] arr = { 10, 20, 30, 40, 50};
int count = arr.Length;
Console.Write("Byte Array... ");
for (int i = 0; i < count; i++) {
Console.Write("
"+arr[i]);
}
Console.WriteLine("
Byte Array (String representation) = {0} ",
BitConverter.ToString(arr));
for (int i = 1; i < arr.Length - 1; i = i + 2) {
ushort res = BitConverter.ToUInt16(arr, i);
Console.WriteLine("
Value = "+arr[i]);
Console.WriteLine("Result = "+res);
}
}
}실행 결과
Byte Array... 10 20 30 40 50 Byte Array (String representation) = 0A-14-1E-28-32 Value = 20 Result = 7700 Value = 40 Result = 12840
결과 분석
루프가 인덱스 1과 3에서 각각 두 바이트씩 읽으면서 결과가 어떻게 나오는지 살펴보겠습니다.
- 인덱스 1 : 바이트 20(0x14)과 30(0x1E) → 20 + 30 × 256 = 7700
- 인덱스 3 : 바이트 40(0x28)과 50(0x32) → 40 + 50 × 256 = 12840
이처럼 앞쪽 바이트가 하위 자릿수에 놓이는 리틀 엔디안 규칙 때문에 단순히 두 숫자를 이어 붙인 값이 아니라 위와 같은 결과가 출력됩니다.
예제 2
using System;
public class Demo {
public static void Main() {
byte[] arr = { 0, 0, 1, 3, 5, 7, 10, 16, 20, 34, 42, 55, 66, 75};
int count = arr.Length;
Console.Write("Byte Array... ");
for (int i = 0; i < count; i++) {
Console.Write("
"+arr[i]);
}
Console.WriteLine("
Byte Array (String representation) = {0} ",
BitConverter.ToString(arr));
for (int i = 1; i < arr.Length - 1; i = i + 2) {
ushort res = BitConverter.ToUInt16(arr, i);
Console.WriteLine("
Value = "+arr[i]);
Console.WriteLine("Result = "+res);
}
}
}실행 결과
Byte Array... 0 0 1 3 5 7 10 16 20 34 42 55 66 75 Byte Array (String representation) = 00-00-01-03-05-07-0A-10-14-22-2A-37-42-4B Value = 0 Result = 256 Value = 3 Result = 1283 Value = 7 Result = 2567 Value = 16 Result = 5136 Value = 34 Result = 10786 Value = 55 Result = 16951
두 번째 예제 역시 같은 원리로 동작합니다. 예를 들어 인덱스 11에서는 바이트 55(0x37)와 66(0x42)을 읽어 55 + 66 × 256 = 16951이 계산됩니다.
사용 시 주의사항 및 예외
- ArgumentNullException :
val이 null인 경우 발생합니다. - ArgumentOutOfRangeException :
startIndex가 0보다 작거나,val.Length - 2보다 큰 경우 발생합니다. - 지정된 인덱스부터 최소 2바이트가 남아 있어야 하므로, 배열 끝부분을 다룰 때는 범위 검증을 먼저 수행하는 것이 안전합니다.