Feedback

String in Byte Array und zurück wandeln

Sprache: C#

Zwei Methoden mit denen man einen String in ein Byte Array und ein Bytearray in einen String wandeln kann.
private byte[] StringToByteArray(string str)
{
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    return enc.GetBytes(str);
}

private string ByteArrayToString(byte[] arr)
{
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    return enc.GetString(arr);
}
private byte[] StringToByteArray(string str)
{
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    return enc.GetBytes(str);
}

private string ByteArrayToString(byte[] arr)
{
    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    return enc.GetString(arr);
}

5 Kommentare

  1. Bitte passt auf mit Encoding. Hier könnte es fix Probleme geben, da .NET UTF verwendet für Strings. Somit muss man immer wieder schauen was man hier macht.

    Gruss,
    Gregor

  2. Zu Encodings sollte wirklich JEDER den Artikel lesen: „The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)“
    http://www.joelonsoftware.com/articles/Unicode.html

    ASCIIEncoding ist meistens nicht gut, weil ASCII keine Umlaute definiert. Besser ist, man weiß, wie sein byte[] kodiert ist und nimmt dann z.B.
    System.Text.Encoding.GetEncoding(1252); (Windows, Latin1)
    System.Text.Encoding.GetEncoding(437); (MS-DOS, DOS-Konsole)
    System.Text.Encoding.UTF8; (Unicode UTF-8)

    Merke: Ein String, von dem man nicht weiß, wie er kodiert ist, ist wertlos.