Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#에서 바이트 배열을 문자열로 변환하는 방법은 무엇입니까?

<시간/>

.Net에서 모든 문자열에는 문자 집합과 인코딩이 있습니다. 문자 인코딩은 컴퓨터에 원시 0과 1을 실제 문자로 해석하는 방법을 알려줍니다. 일반적으로 숫자와 문자를 짝지어서 이 작업을 수행합니다. 실제로 유니코드 문자 집합을 바이트 시퀀스로 변환하는 과정입니다.

Encoding.GetString 메서드(Byte[])를 사용하여 지정된 바이트 배열의 모든 바이트를 문자열로 디코딩할 수 있습니다. UTF8, Unicode, UTF32, ASCII 등과 같은 Encoding 클래스에서 여러 다른 디코딩 체계도 사용할 수 있습니다. Encoding 클래스는 System.Text 네임스페이스의 일부로 사용할 수 있습니다.

string result = Encoding.Default.GetString(byteArray);

예시

using System;
using System.Text;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         byte[] byteArray = Encoding.Default.GetBytes("Hello World");
         Console.WriteLine($"Byte Array is: {string.Join(" ", byteArray)}");
         string str = Encoding.Default.GetString(byteArray);
         Console.WriteLine($"String is: {str}");
         Console.ReadLine();
      }
   }
}

출력

위 코드의 출력은

Byte Array is: 72 101 108 108 111 32 87 111 114 108 100
String is: Hello World

양방향에 대해 동일한 인코딩을 사용해야 한다는 점에 유의하는 것이 중요합니다. 예를 들어, 바이트 배열이 ASCII로 인코딩되어 있고 UTF32를 사용하여 문자열을 얻으려고 하면 원하는 문자열을 얻을 수 없습니다.

예시

using System;
using System.Text;
namespace DemoApplication {
   public class Program {
      static void Main(string[] args) {
         byte[] byteArray = Encoding.ASCII.GetBytes("Hello World");
         Console.WriteLine($"Byte Array is: {string.Join(" ", byteArray)}");
         string str = Encoding.UTF32.GetString(byteArray);
         Console.WriteLine($"String is: {str}");
         Console.ReadLine();
      }
   }
}

출력

위 코드의 출력은

Byte Array is: 72 101 108 108 111 32 87 111 114 108 100
String is: ???