Comment obtenir une représentation cohérente en octets des chaînes de caractères en C# sans spécifier manuellement un encodage ?

Comment convertir une "chaîne" en "octet[]" dans .NET (C#) sans spécifier manuellement un encodage spécifique ?

Je vais crypter la chaîne. Je peux la crypter sans la convertir, mais j&#8217aimerais quand même savoir pourquoi l&#8217encodage entre en jeu ici.

De même, pourquoi l'encodage doit-il entrer en ligne de compte ? Ne puis-je pas simplement obtenir les octets dans lesquels la chaîne a été stockée ? Pourquoi y a-t-il une dépendance vis-à-vis des codages de caractères ?

Cela dépend de l'encodage de votre chaîne ([ASCII][1], [UTF-8][2], ...).

Par exemple :

byte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString);
byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString);

Un petit exemple de l'importance de l'encodage :

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 '?'

L'ASCII n'est tout simplement pas équipé pour traiter les caractères spéciaux.

En interne, le cadre .NET utilise [UTF-16][3] pour représenter les chaînes de caractères, donc si vous voulez simplement obtenir les octets exacts que .NET utilise, utilisez System.Text.Encoding.Unicode.GetBytes (...).

Voir [Character Encoding in the .NET Framework][4] (MSDN) pour plus d'informations.

[1] : http://en.wikipedia.org/wiki/ASCII [2] : http://en.wikipedia.org/wiki/UTF-8 [3] : https://en.wikipedia.org/wiki/UTF-16 [4] : http://msdn.microsoft.com/en-us/library/ms404377.aspx

Commentaires (9)
byte[] strToByteArray(string str)
{
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    return enc.GetBytes(str);
}
Commentaires (3)
// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
    System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
    return encoding.GetBytes(str);
}

// C# to convert a byte array to a string.
byte [] dBytes = ...
string str;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(dBytes);
Commentaires (1)