System.Text.Encoding 的用法 - 字串與 byte 互轉
C# 範例為
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string input = "a";
byte[] b = System.Text.Encoding.GetEncoding(950).GetBytes(input);
foreach (var item in b)
{
Console.WriteLine(item);
}
string output = System.Text.Encoding.GetEncoding(950).GetString(b);
Console.WriteLine("output = " + output);
Console.WriteLine();
byte[] d = System.Text.Encoding.Default.GetBytes(input);
foreach (var item in d)
{
Console.WriteLine(item);
}
string output2 = System.Text.Encoding.Default.GetString(d);
Console.WriteLine("output2 = " + output2);
Console.ReadKey();
}
}
}
VB.NET 範例為
Module Module1 Sub Main() Dim abData() As Byte Dim Str As String Dim i As Long Str = "Hello world!" ' Convert string to bytes abData = System.Text.Encoding.Default.GetBytes(Str) For i = 0 To UBound(abData) Console.WriteLine(Hex(abData(i)) & "='" & Chr(abData(i)) & "'") Next ' Convert bytes to string Str = System.Text.Encoding.Default.GetString(abData) Console.WriteLine("'" & Str & "'") Console.ReadKey() End Sub End Module
參考資料: