Pergunta

Eu tenho uma matriz byte[] que é carregado a partir de um arquivo que eu aconteço conhecido contém UTF-8 . Em algum código de depuração, eu preciso convertê-lo em uma corda. Existe um um forro que vai fazer isso?

Nos bastidores deve ser apenas uma atribuição e uma memcopy , por isso mesmo se não for implementado, deve ser possível.

Foi útil?

Solução

string result = System.Text.Encoding.UTF8.GetString(byteArray);

Outras dicas

Não é pelo menos quatro maneiras diferentes, fazendo essa conversão.

  1. O Encoding GetString
    , mas você não será capaz de obter os bytes originais de volta se esses bytes têm caracteres não-ASCII.

  2. BitConverter.ToString
    A saída é um "-". Cadeia delimitada, mas não há nenhuma .NET built-in método para converter parte de trás string para array de bytes

  3. Convert.ToBase64String Como você pode facilmente converter parte de trás cadeia de saída a matriz de bytes usando Convert.FromBase64String
    . Nota: A cadeia de saída pode conter '+', '/ 'e '='. Se você quiser usar a corda em uma URL, você precisa codificá-lo explicitamente.

  4. HttpServerUtility.UrlTokenEncode Como você pode facilmente converter a seqüência de saída traseira para matriz de bytes usando HttpServerUtility.UrlTokenDecode. A cadeia de saída já está URL amigável! A desvantagem é que ele precisa System.Web montagem se o projeto não é um projeto web.

Um exemplo completo:

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

A solução geral para converter a partir de matriz de bytes para cadeia quando você não sabe a codificação:

static string BytesToStringConverted(byte[] bytes)
{
    using (var stream = new MemoryStream(bytes))
    {
        using (var streamReader = new StreamReader(stream))
        {
            return streamReader.ReadToEnd();
        }
    }
}

Definição:

public static string ConvertByteToString(this byte[] source)
{
    return source != null ? System.Text.Encoding.UTF8.GetString(source) : null;
}

Usando:

string result = input.ConvertByteToString();

A conversão de um byte[] a um string parece simples, mas qualquer tipo de codificação é provável que estragar a cadeia de saída. Esta função pouco simplesmente funciona sem quaisquer resultados inesperados:

private string ToString(byte[] bytes)
{
    string response = string.Empty;

    foreach (byte b in bytes)
        response += (Char)b;

    return response;
}

Usando (byte)b.ToString("x2"), saídas 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;
    }

}

Há também classe UnicodeEncoding, bastante simples em uso:

ByteConverter = new UnicodeEncoding();
string stringDataForEncoding = "My Secret Data!";
byte[] dataEncoded = ByteConverter.GetBytes(stringDataForEncoding);

Console.WriteLine("Data after decoding: {0}", ByteConverter.GetString(dataEncoded));

Como alternativa:

 var byteStr = Convert.ToBase64String(bytes);

A Linq one-liner para converter um byteArrFilename matriz de bytes lidos de um arquivo para uma string puro ascii C-style terminada em zero seria esta:. Útil para ler coisas como tabelas de índice de arquivos em formatos de arquivo antigos

String filename = new String(byteArrFilename.TakeWhile(x => x != 0)
                              .Select(x => x < 128 ? (Char)x : '?').ToArray());

Eu uso '?' como char padrão para qualquer coisa puro ascii aqui, mas que pode ser mudado, é claro. Se você quer ter certeza de que você pode detectá-lo, basta usar '\0' em vez disso, uma vez que o TakeWhile nos assegura de início que uma corda construídas desta forma não pode conter valores '\0' da fonte de entrada.

classe BitConverter pode ser usado para converter um byte[] para string.

var convertedString = BitConverter.ToString(byteAttay);

Documentação da classe BitConverter pode ser fonte de MSDN

Para minha nenhum conhecimento das respostas dadas garantir o comportamento correto com terminação nula. Até que alguém me mostra de forma diferente eu escrevi minha própria classe estática para manusear este com os seguintes métodos:

// 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);
}

A razão para o startIndex era no exemplo I foi trabalhar no especificamente I necessário para analisar uma byte[] como uma matriz de terminada nula cordas. Ele pode ser ignorada no caso simples

hier é um resultado onde não tinha que se preocupar com a codificação. Usei-o na minha classe de rede e enviar objetos binários como cordas com ele.

        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);
        }

Além da resposta selecionada, se você estiver usando .NET35 ou .NET35 CE, você tem que especificar o índice do primeiro byte para decodificar e o número de bytes de decodificação:

string result = System.Text.Encoding.UTF8.GetString(byteArray,0,byteArray.Length);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top