Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

แปลง Byte Array เป็น String ใน C#

String ใน .NET มี Encoding ต้องใช้ Encoding เดียวกันทั้ง Encode/Decode

ใช้ Encoding.GetString()

using System.Text;

byte[] bytes = Encoding.Default.GetBytes("Hello World");
string str = Encoding.Default.GetString(bytes); // "Hello World"

Encoding ที่ใช้บ่อย

  • Encoding.UTF8 - มาตรฐานเว็บ (แนะนำ)
  • Encoding.Unicode - UTF-16 (Windows Default)
  • Encoding.ASCII - เฉพาะ ASCII 0-127
  • Encoding.Default - System ANSI Code Page (ขึ้นกับ OS/Region)

ตัวอย่างเต็ม

byte[] bytes = Encoding.Default.GetBytes("Hello World");
Console.WriteLine($"Bytes: {string.Join(" ", bytes)}");
// 72 101 108 108 111 32 87 111 114 108 100

string str = Encoding.Default.GetString(bytes);
Console.WriteLine($"String: {str}"); // Hello World

⚠ สำคัญ: ต้องใช้ Encoding เดียวกัน

// ผิด: Encode ASCII, Decode UTF32
byte[] bytes = Encoding.ASCII.GetBytes("Hello World");
string wrong = Encoding.UTF32.GetString(bytes); // "???"

Output:

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

ต้อง Encode/Decode ด้วย Encoding ตัวเดียวกันเสมอ