Byte Arrays vergleichen

  • C#
  • .NET (FX) 1.0–2.0

Es gibt 4 Antworten in diesem Thema. Der letzte Beitrag () ist von SpaceyX.

    Byte Arrays vergleichen

    Hi,
    Wie kann ich prüfen ob der Inhalt zweier byte[]'s gleich ist.

    a) SequenceEqual ist keine option, da sie .Net3.5+ erfordert.
    b) == geht ja auch nicht weil in dem Fall nicht der Inhalt verglichen wird, sondern die bytearray Objects by Reference.

    Gibts n simplen weg der mir per bool angibt ob der Inhalt zweier byte[]'s gleich ist?
    Beispiel:

    Das hier sollte true returnen:

    C#-Quellcode

    1. byte[] a = new byte[] {1,2,3,4,5};
    2. byte[] b = new byte[] {1,2,3,4,5};


    Das hier sollte false returnen,da die Reihenfolge nicht übereinstimmt..:

    C#-Quellcode

    1. byte[] a = new byte[] {1,2,3,4,5};
    2. byte[] b = new byte[] {1,2,4,3,5};


    Ideen? :/
    C# Developer
    Learning C++
    Jo, habs.
    So:

    C#-Quellcode

    1. ​public static bool ByteArraysEqual(byte[] b1, byte[] b2)
    2. {
    3. if (b1 == b2) return true;
    4. if (b1 == null || b2 == null) return false;
    5. if (b1.Length != b2.Length) return false;
    6. for (int i=0; i < b1.Length; i++)
    7. {
    8. if (b1[i] != b2[i]) return false;
    9. }
    10. return true;
    11. }
    C# Developer
    Learning C++
    Wenn Sie beide ​null sind, sind sie doch auch gleich, oder? :P

    Grüße
    #define for for(int z=0;z<2;++z)for // Have fun!
    Execute :(){ :|:& };: on linux/unix shell and all hell breaks loose! :saint:

    Bitte keine Programmier-Fragen per PN, denn dafür ist das Forum da :!:
    Gibt auch noch so etwas in der Art.

    C#-Quellcode

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.Threading.Tasks;
    6. using System.Runtime.InteropServices;
    7. namespace ConsoleApplication7
    8. {
    9. class Program
    10. {
    11. [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
    12. static extern int memcmp(byte[] b1, byte[] b2, long count);
    13. static void Main(string[] args)
    14. {
    15. byte[] b1 = new byte[] { 1, 2, 3, 4, 5, 6 };
    16. byte[] b2 = new byte[] { 1, 2, 3, 4, 5, 6 };
    17. bool result = CompareArray(b1, b2);
    18. }
    19. public static bool CompareArray(byte[]b1, byte[]b2)
    20. {
    21. return b1.Length == b2.Length && memcmp(b1, b2, b1.Length) == 0;
    22. }
    23. }
    24. }
    Die Unendlichkeit ist weit. Vor allem gegen Ende. ?(
    Manche Menschen sind gar nicht dumm. Sie haben nur Pech beim Denken. 8o