1

I need to get the bytes from an array of bytes starting at a certain index and for a certain length (4). How can I get this?

Note: I don't want to use the Array.copy sub as it is not a function. I need to put it in something like Sub MySub([argument as byte()]the_function_I_Need(Array, index, length)).

1
  • Is this an array of bytes? If not, can you be more specific about the array type? Commented Jan 5, 2010 at 19:59

2 Answers 2

3

Something like:

Dim portion As Byte() = New Byte(length - 1) {}
Array.Copy(originalArray, index, portion, 0, length)

The "- 1" is because of VB taking the last element index rather than the size.

EDIT: I missed the bit about not wanting to use Array.Copy. (Was it there when I posted the answer, or did you edit it in within the five minutes "grace period"?)

Just wrap this into a method if you really need to. While there are alternatives using LINQ etc, this will be the most efficient way of doing it if you genuinely want a new array.

There's also ArraySegment(Of T) if you're happy to use a wrapper around the existing array - but that's not the same thing.

Sign up to request clarification or add additional context in comments.

5 Comments

"I don't want to use the Array.copy", I know about that but I need something where the bytes are returned so I don't have to have the Dim portion
@Jonathan: you wrap array.copy in a function.
I know I have done that in the mean time just wanted to know if there was an "out the box" way?
arr.Skip(index).Take(length).ToArray() perhaps?
@Jonathan: Doh - missed that bit of the question, sorry. Just write it as a method if you really have to. Will edit.
0
Private Function the_function_you_need(ByVal arr As Byte(), ByVal ix As Integer, _
    ByVal len As Integer) As Byte()

    Dim arr2 As Byte() = New Byte(len - 1)
    Array.Copy(arr, ix, arr2, 0, len)
    Return arr2

End Function

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.