Hvordan får jeg en konsistent byte-repræsentation af strenge i C# uden manuelt at angive en kodning?

Hvordan konverterer jeg en string til en byte[] i .NET (C#) uden manuelt at angive en bestemt kodning?

Jeg har tænkt mig at kryptere strengen. Jeg kan kryptere den uden at konvertere, men jeg vil stadig gerne vide, hvorfor kodning kommer i spil her.

Desuden, hvorfor skal kodning tages i betragtning? Kan jeg ikke bare få fat i hvilke bytes strengen er blevet gemt i? Hvorfor er der en afhængighed af tegnkodninger?

Det afhænger af kodningen af din streng (ASCII, UTF-8, ...).

For eksempel:

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

Et lille eksempel på, hvorfor kodning har betydning:

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

ASCII er simpelthen ikke udstyret til at håndtere specialtegn.

Internt bruger .NET-rammen UTF-16 til at repræsentere strenge, så hvis du blot ønsker at få de nøjagtige bytes, som .NET bruger, skal du bruge System.Text.Encoding.Unicode.GetBytes (...).

Se Character Encoding in the .NET Framework (MSDN) for at få flere oplysninger.

Kommentarer (9)
byte[] strToByteArray(string str)
{
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    return enc.GetBytes(str);
}
Kommentarer (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);
Kommentarer (1)