.net - Comment obtenir une représentation régulière des octets dans C# sans spécifier manuellement un encodage

Mots clés : c#.netstringcharacter-encodingc#

meilleur 4 Réponses .net - Comment obtenir une représentation régulière des octets dans C# sans spécifier manuellement un encodage

vote vote

95

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; }  // Do NOT use on arbitrary bytes; only use on GetBytes's output on the SAME system 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); } 
vote vote

88

byte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString); byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString); 
string pi = "\u03a0"; byte[] ascii = System.Text.Encoding.ASCII.GetBytes (pi); byte[] utf8 = System.Text.Encoding.UTF8.GetBytes (pi);  Console.WriteLine (ascii.Length); //Will print 1 Console.WriteLine (utf8.Length); //Will print 2 Console.WriteLine (System.Text.Encoding.ASCII.GetString (ascii)); //Will print '?' 
vote vote

80

const string data = "A string with international characters: Norwegian: ÆØÅæøå, Chinese: 喂 谢谢"; var bytes = System.Text.Encoding.UTF8.GetBytes(data); var decoded = System.Text.Encoding.UTF8.GetString(bytes); 
vote vote

68

BinaryFormatter bf = new BinaryFormatter(); byte[] bytes; MemoryStream ms = new MemoryStream();  string orig = "喂 Hello 谢谢 Thank You"; bf.Serialize(ms, orig); ms.Seek(0, 0); bytes = ms.ToArray();  MessageBox.Show("Original bytes Length: " + bytes.Length.ToString());  MessageBox.Show("Original string Length: " + orig.Length.ToString());  for (int i = 0; i < bytes.Length; ++i) bytes[i] ^= 168; // pseudo encrypt for (int i = 0; i < bytes.Length; ++i) bytes[i] ^= 168; // pseudo decrypt  BinaryFormatter bfx = new BinaryFormatter(); MemoryStream msx = new MemoryStream();             msx.Write(bytes, 0, bytes.Length); msx.Seek(0, 0); string sx = (string)bfx.Deserialize(msx);  MessageBox.Show("Still intact :" + sx);  MessageBox.Show("Deserialize string Length(still intact): "      + sx.Length.ToString());  BinaryFormatter bfy = new BinaryFormatter(); MemoryStream msy = new MemoryStream(); bfy.Serialize(msy, sx); msy.Seek(0, 0); byte[] bytesy = msy.ToArray();  MessageBox.Show("Deserialize bytes Length(still intact): "     + bytesy.Length.ToString()); 

Questions similaires