views:

354

answers:

2

I need to get the bytes from an array of bytes starting at a certain index and for a certain length (4), how can 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([arguement as byte()]the_function_I_Need(Array, index, length))

+1  A: 

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.

Jon Skeet
"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
@Jonathan: you wrap array.copy in a function.
Joel Coehoorn
I know I have done that in the mean time just wanted to know if there was an "out the box" way?
Jonathan
arr.Skip(index).Take(length).ToArray() perhaps?
Hans Passant
@Jonathan: Doh - missed that bit of the question, sorry. Just write it as a method if you really have to. Will edit.
Jon Skeet
A: 
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
Andy West