0

I read a an array of bytes from a file I pass this to a class that then assigns various bytes from that array to various members of varying sizes.

Ideally i would like to do something like this

memberThatIsAUShort = bitconverter.ToUShort(tempArray.subArray(3,5))
memberThatIsAShort = bitconverter.ToShort(tempArray.subArray(6,8))

Instead of looping through the array, copying the bytes to new shorter array and passing them in.

michael
  • 2,577
  • 5
  • 39
  • 62

2 Answers2

1

You would do this as:

memberThatIsAUShort = BitConverter.ToUInt16(tempArray,3)
memberThatIsAShort = BitConverter.ToInt16(tempArray,6)

These methods are both static (hence BitConverter casing), and already provide a startIndex parameter. Since BitConverter already knows the appropriate number of bytes for a short/ushort, you don't need to specify end indices. For details, see BitConverter.ToUInt16 and BitConverter.ToInt16.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

Although your syntax is wrong, I think I understand your intent and believe that something like this answer will suit you fine:

Array Slices in C#

Community
  • 1
  • 1
Marc
  • 9,254
  • 2
  • 29
  • 31
  • This really somewhat answers the question, but doesn't solve the actual problem that the OP is trying to solve. No array manipulation is required, just conversion. – Reed Copsey Aug 03 '10 at 18:01
  • I agree, leaving it for the sake of answering future slice questions. +1 to your answer. – Marc Aug 03 '10 at 18:03