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

后端 未结 15 2497
迷失自我
迷失自我 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条回答
  •  余生分开走
    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);
            }
    

提交回复
热议问题