Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# BitConverter.ToString(Byte[]) 메서드 완벽 가이드 - 바이트 배열을 16진수 문자열로 변환하기

C#의 BitConverter.ToString() 메서드는 지정된 바이트 배열(byte[])의 각 요소에 해당하는 숫자 값을 16진수 문자열 표현으로 변환하는 데 사용됩니다. 각 바이트 값은 두 자리 16진수로 변환되며, 하이픈(-)으로 구분된 형태의 문자열이 반환됩니다.

문법(Syntax)

public static string ToString (byte[] val);

위 문법에서 val은 변환할 대상이 되는 바이트 배열입니다.

예제 1: 기본적인 사용법

다음 예제에서는 바이트 배열을 생성한 후, 배열의 각 요소를 출력하고 BitConverter.ToString() 메서드를 사용하여 16진수 문자열로 변환합니다.

using System;
public class Demo {
   public static void Main() {
      byte[] arr = {0, 10, 2, 5, 32, 45};
      int count = arr.Length;
      Console.Write("Byte Array... ");
      for (int i = 0; i < count; i++) {
         Console.Write("\n"+arr[i]);
      }
      Console.WriteLine("\nByte Array (String representation) = {0} ",
      BitConverter.ToString(arr));
   }
}

출력 결과

Byte Array...
0
10
2
5
32
45
Byte Array (String representation) = 00-0A-02-05-20-2D

실행 결과를 보면 각 10진수 바이트 값이 2자리 16진수로 변환된 것을 확인할 수 있습니다. 예를 들어 10진수 10은 16진수 0A로, 32는 20으로, 45는 2D로 변환되었습니다.

예제 2: ToInt16과 함께 활용하기

다음 예제에서는 BitConverter.ToString()으로 배열 전체를 16진수 문자열로 표시하고, 추가로 BitConverter.ToInt16() 메서드를 사용하여 인접한 두 바이트씩 묶어 16비트 정수(short) 값으로 변환하는 과정을 보여줍니다.

using System;
public class Demo {
   public static void Main() {
      byte[] arr = { 0, 0, 7, 10, 18, 20, 25, 26, 32};
      int count = arr.Length;
      Console.Write("Byte Array... ");
      for (int i = 0; i < count; i++) {
         Console.Write("\n"+arr[i]);
      }
      Console.WriteLine("\nByte Array (String representation) = "+BitConverter.ToString(arr));
      for (int i = 0; i < arr.Length - 1; i = i + 2) {
         short res = BitConverter.ToInt16(arr, i);
         Console.WriteLine("\nValue = "+arr[i]);
         Console.WriteLine("Result = "+res);
      }
   }
}

출력 결과

Byte Array...
0
0
7
10
18
20
25
26
32
Byte Array (String representation) = 00-00-07-0A-12-14-19-1A-20
Value = 0
Result = 0
Value = 7
Result = 2567
Value = 18
Result = 5138
Value = 25
Result = 6681

BitConverter.ToInt16(arr, i)는 시작 인덱스 i부터 2바이트를 읽어 little-endian 방식으로 short 타입의 정수로 변환합니다. 예를 들어 인덱스 2부터 읽으면 바이트 7(0x07)과 10(0x0A)이 결합되어 0x0A07, 즉 2567이라는 결과가 나옵니다.

정리

BitConverter.ToString() 메서드는 디버깅 시 바이트 데이터를 사람이 읽기 쉬운 16진수 형태로 확인하거나, 네트워크 프로토콜 분석, 해시 값 출력 등 다양한 상황에서 유용하게 활용됩니다. 특히 바이트 배열의 내용을 로그로 남기거나 화면에 표시해야 할 때 필수적인 메서드입니다.