UTF-8 byte []を文字列に変換する方法は?
-
05-07-2019 - |
質問
カバーの下では、単なる割り当てと memcopy である必要があるため、実装されていなくても可能です。
解決
string result = System.Text.Encoding.UTF8.GetString(byteArray);
他のヒント
この変換を行うには、少なくとも4つの異なる方法があります。
-
エンコーディングのGetString
。ただし、元のバイトにASCII以外の文字が含まれている場合、元のバイトを取得することはできません。 -
BitConverter.ToString
出力は"-"です。区切り文字列ですが、文字列をバイト配列に戻すための.NET組み込みメソッドはありません。 -
Convert.ToBase64String
Convert.FromBase64String
を使用すると、出力文字列を簡単にバイト配列に変換できます。
注:出力文字列には「+」、「/」、「=」を含めることができます。 URLで文字列を使用する場合は、明示的にエンコードする必要があります。 -
HttpServerUtility.UrlTokenEncode
HttpServerUtility.UrlTokenDecode
を使用すると、出力文字列を簡単にバイト配列に変換できます。出力文字列はすでにURLフレンドリーです!欠点は、プロジェクトがWebプロジェクトでない場合、System.Web
アセンブリが必要なことです。
完全な例:
byte[] bytes = { 130, 200, 234, 23 }; // A byte array contains non-ASCII (or non-readable) characters
string s1 = Encoding.UTF8.GetString(bytes); // ���
byte[] decBytes1 = Encoding.UTF8.GetBytes(s1); // decBytes1.Length == 10 !!
// decBytes1 not same as bytes
// Using UTF-8 or other Encoding object will get similar results
string s2 = BitConverter.ToString(bytes); // 82-C8-EA-17
String[] tempAry = s2.Split('-');
byte[] decBytes2 = new byte[tempAry.Length];
for (int i = 0; i < tempAry.Length; i++)
decBytes2[i] = Convert.ToByte(tempAry[i], 16);
// decBytes2 same as bytes
string s3 = Convert.ToBase64String(bytes); // gsjqFw==
byte[] decByte3 = Convert.FromBase64String(s3);
// decByte3 same as bytes
string s4 = HttpServerUtility.UrlTokenEncode(bytes); // gsjqFw2
byte[] decBytes4 = HttpServerUtility.UrlTokenDecode(s4);
// decBytes4 same as bytes
エンコードがわからない場合にバイト配列から文字列に変換する一般的なソリューション:
static string BytesToStringConverted(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
{
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
定義:
public static string ConvertByteToString(this byte[] source)
{
return source != null ? System.Text.Encoding.UTF8.GetString(source) : null;
}
使用方法:
string result = input.ConvertByteToString();
byte []
を string
に変換するのは簡単に思えますが、どのような種類のエンコードでも出力文字列を台無しにする可能性があります。この小さな機能は、予期しない結果なしで機能します。
private string ToString(byte[] bytes)
{
string response = string.Empty;
foreach (byte b in bytes)
response += (Char)b;
return response;
}
(byte)b.ToString(&quot; x2&quot;)
を使用して、出力 b4b5dfe475e58b67
public static class Ext {
public static string ToHexString(this byte[] hex)
{
if (hex == null) return null;
if (hex.Length == 0) return string.Empty;
var s = new StringBuilder();
foreach (byte b in hex) {
s.Append(b.ToString("x2"));
}
return s.ToString();
}
public static byte[] ToHexBytes(this string hex)
{
if (hex == null) return null;
if (hex.Length == 0) return new byte[0];
int l = hex.Length / 2;
var b = new byte[l];
for (int i = 0; i < l; ++i) {
b[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return b;
}
public static bool EqualsTo(this byte[] bytes, byte[] bytesToCompare)
{
if (bytes == null && bytesToCompare == null) return true; // ?
if (bytes == null || bytesToCompare == null) return false;
if (object.ReferenceEquals(bytes, bytesToCompare)) return true;
if (bytes.Length != bytesToCompare.Length) return false;
for (int i = 0; i < bytes.Length; ++i) {
if (bytes[i] != bytesToCompare[i]) return false;
}
return true;
}
}
クラスUnicodeEncodingもあり、使用方法は非常に簡単です:
ByteConverter = new UnicodeEncoding();
string stringDataForEncoding = "My Secret Data!";
byte[] dataEncoded = ByteConverter.GetBytes(stringDataForEncoding);
Console.WriteLine("Data after decoding: {0}", ByteConverter.GetString(dataEncoded));
別の方法:
var byteStr = Convert.ToBase64String(bytes);
ファイルから読み取られたバイト配列 byteArrFilename
を純粋なASCII Cスタイルのゼロ終了文字列に変換するためのLinqワンライナーは次のようになります。古いファイルインデックステーブルのようなものを読むのに便利アーカイブ形式。
String filename = new String(byteArrFilename.TakeWhile(x => x != 0)
.Select(x => x < 128 ? (Char)x : '?').ToArray());
'?'
をここでは純粋なascii以外のデフォルト文字として使用していますが、もちろん変更できます。確実に検出できるようにしたい場合は、代わりに '\ 0'
を使用してください。最初の TakeWhile
は、この方法で構築された文字列に< code> '\ 0' 入力ソースからの値。
BitConverter
クラスを使用して、 byte []
を string
に変換できます。
var convertedString = BitConverter.ToString(byteAttay);
BitConverter
クラスのドキュメントは、 MSDN
私の知る限りでは、与えられた答えはどれもヌル終端での正しい動作を保証しません。誰かが私に違うことを示すまで、私はこれを次のメソッドで処理するための独自の静的クラスを作成しました:
// Mimics the functionality of strlen() in c/c++
// Needed because niether StringBuilder or Encoding.*.GetString() handle \0 well
static int StringLength(byte[] buffer, int startIndex = 0)
{
int strlen = 0;
while
(
(startIndex + strlen + 1) < buffer.Length // Make sure incrementing won't break any bounds
&& buffer[startIndex + strlen] != 0 // The typical null terimation check
)
{
++strlen;
}
return strlen;
}
// This is messy, but I haven't found a built-in way in c# that guarentees null termination
public static string ParseBytes(byte[] buffer, out int strlen, int startIndex = 0)
{
strlen = StringLength(buffer, startIndex);
byte[] c_str = new byte[strlen];
Array.Copy(buffer, startIndex, c_str, 0, strlen);
return Encoding.UTF8.GetString(c_str);
}
startIndex
の理由は、特に byte []
をヌルで終了する文字列の配列として解析する必要がある作業中の例にありました。単純なケースでは安全に無視できます
hierは、エンコードに煩わされる必要がない結果です。ネットワーククラスで使用し、バイナリオブジェクトを文字列として送信します。
public static byte[] String2ByteArray(string str)
{
char[] chars = str.ToArray();
byte[] bytes = new byte[chars.Length * 2];
for (int i = 0; i < chars.Length; i++)
Array.Copy(BitConverter.GetBytes(chars[i]), 0, bytes, i * 2, 2);
return bytes;
}
public static string ByteArray2String(byte[] bytes)
{
char[] chars = new char[bytes.Length / 2];
for (int i = 0; i < chars.Length; i++)
chars[i] = BitConverter.ToChar(bytes, i * 2);
return new string(chars);
}
.NET 35または.NET35 CEを使用している場合、選択した回答に加えて、デコードする最初のバイトのインデックスとデコードするバイト数を指定する必要があります。
string result = System.Text.Encoding.UTF8.GetString(byteArray,0,byteArray.Length);