convert byte[] to short[] in C#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • eyalbi007
    New Member
    • Mar 2008
    • 4

    convert byte[] to short[] in C#

    Hi all,

    I need to perfom simple-looking task in C#: Converting byte array to short array - meaning that if my byte array has 100 cells, my short array will have 50 cells.

    If it was C/C++ it was simple, using pointers. However in C# I just can't do it - I've already tried using 'unsafe' block and memory pinning using GCHandle, with no success.

    Another thing that bothers me in the solutions I found is that the conversion is done using memory copying, which is not necessary, since all the information is already there!

    I'll be grateful for any solution!

    Thanks,

    Eyal.
  • Plater
    Recognized Expert Expert
    • Apr 2007
    • 7872

    #2
    EDIT:OOPS!


    Ok so you want say the first two bytes in the byte[] to be the first short in the short[] and so on and so on?
    You're going to need to do some type casting I think.
    Either that or use BitConverter and BinaryStream?

    Comment

    • eyalbi007
      New Member
      • Mar 2008
      • 4

      #3
      Originally posted by Plater
      EDIT:OOPS!


      Ok so you want say the first two bytes in the byte[] to be the first short in the short[] and so on and so on?
      You're going to need to do some type casting I think.
      Either that or use BitConverter and BinaryStream?
      Hi,

      Both solutions you suggested can do the trick, but only inside a for loop - and I need to cast the byte array to short array in one command, since it's very long array.

      Comment

      • Plater
        Recognized Expert Expert
        • Apr 2007
        • 7872

        #4
        Can you use Array.Copy()?
        You *might* be able to abuse an array of structs with custom marshalling assigned. But I have no idea how to do that.

        Comment

        Working...