views:

182

answers:

3

What is the easiest way to ensure there are no duplicates and a byte array is in order, say from a network connection?

+2  A: 

create an array of 256 booleans and iterate over the byte array one by one.

set each value in the array to true when you encounter it. if you encounter an already true value then the byte array is in an invalid format

I don't quite follow what you mean by the "byte array is in order" bit

You could also use a bitarray

example:

bool CheckForDuplicates(byte[] arr)
    {
        bool[] map = new bool[256];

        foreach (byte b in arr)
        {
            if (map[b] == true)
                return false;
            map[b] = true;
        }
        return true;
    }
obelix
+ 1, but the if (map[b] == true) should really just be if (map[b]). Personal preference I guess.
Kleinux
+3  A: 

If you're on .NET 3.5, it's pretty easy to get unique items ...

var ba = new byte[6];

ba[0] = 1;
ba[1] = 1;
ba[2] = 2;
ba[2] = 2;
ba[3] = 3;
ba[4] = 4;
ba[5] = 4;

var res = ba.Distinct().ToArray();  // unique

Can you explain what you mean by "in order"?

JP Alioto
+1  A: 

if you don't what to throw an exception or such if the same value is encountered twice you could do:

var set = new HashSet<byte>(byteArray);

if you by being in order mean sorted you can call the LINQ extension method Sort on the object set from above

Rune FS