@manhng

Welcome to my blog!

Byte To String - String To Byte

November 10, 2017 13:44

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?


static
byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } static string GetString(byte[] bytes) { char[] chars = new char[bytes.Length / sizeof(char)]; System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); return new string(chars); }

Categories

Recent posts