5

I have a program that has a byte array that varies in size, but is around 2300 bytes. What I want to do is create a function that will create a new byte array, removing all bytes that I pass to it. For example:

byte[] NewArray = RemoveBytes(OldArray,0xFF);

I need a function that will remove any bytes equal to 0xFF and return me a new byte array.

Any help would be appreciated. I am using C#, by the way.

1
  • if it varies in size, it's more of a collection than an array. But I understand the need to use arrays to emulate the collection for use with older apis. Commented Oct 17, 2010 at 16:55

2 Answers 2

15

You could use the Where extension method to filter the array:

byte[] newArray = oldArray.Where(b => b != 0xff).ToArray();

or if you want to remove multiple elements you could use the Except extension method:

byte[] newArray = oldArray.Except(new byte[] { 0xff, 0xaa }).ToArray();
Sign up to request clarification or add additional context in comments.

2 Comments

Concise. Super helpful.
Note, Except is the set difference. So every remaining byte is only returned one time. In my case printData.Except(bytesToRemove).ToArray() doesn't get the expected output, while printData.Where(e => bytesToRemove.All(b => b != e)).ToArray() works fine.
-1

Break the problem down:

Can you write code to copy from one array to another?

Can you write a conditional?

Can you allocate a new array?

If you are stuck on one of these then ask specifically about it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.