How to convert UTF-8 byte[] to string?

后端 未结 15 2328
迷失自我
迷失自我 2020-11-22 03:11

I have a byte[] array that is loaded from a file that I happen to known contains UTF-8.

In some debugging code, I need to convert it to a string. Is

相关标签:
15条回答
  • BitConverter class can be used to convert a byte[] to string.

    var convertedString = BitConverter.ToString(byteAttay);
    

    Documentation of BitConverter class can be fount on MSDN

    0 讨论(0)
  • 2020-11-22 03:36

    hier is a result where you didnt have to bother with encoding. I used it in my network class and send binary objects as string with it.

            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);
            }
    
    0 讨论(0)
  • 2020-11-22 03:37

    Converting a byte[] to a string seems simple but any kind of encoding is likely to mess up the output string. This little function just works without any unexpected results:

    private string ToString(byte[] bytes)
    {
        string response = string.Empty;
    
        foreach (byte b in bytes)
            response += (Char)b;
    
        return response;
    }
    
    0 讨论(0)
  • 2020-11-22 03:39
    string result = System.Text.Encoding.UTF8.GetString(byteArray);
    
    0 讨论(0)
  • 2020-11-22 03:39

    A Linq one-liner for converting a byte array byteArrFilename read from a file to a pure ascii C-style zero-terminated string would be this: Handy for reading things like file index tables in old archive formats.

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

    I use '?' as default char for anything not pure ascii here, but that can be changed, of course. If you want to be sure you can detect it, just use '\0' instead, since the TakeWhile at the start ensures that a string built this way cannot possibly contain '\0' values from the input source.

    0 讨论(0)
  • 2020-11-22 03:44

    Definition:

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

    Using:

    string result = input.ConvertByteToString();
    
    0 讨论(0)
提交回复
热议问题