-3

I would like to duplicate following C logic in C# if possible:

void f(unsigned char *byteArr)
{
  short *shArr = (short*)byteArr; // shArr[0] = -8, shArr[1] = -265
}
unsigned char byteArr[4];
byteArr[0] = 248;
byteArr[1] = 255;
byteArr[2] = 247;
byteArr[3] = 254;
f(byteArr);

So in C# I have

void f(byte[] byteArr)
{
  short[] shArr = ?
}

and would like shArr to be {-8, -265}. (How) is this possible?

grunt
  • 662
  • 1
  • 8
  • 24
  • 4
    It very much looks like you are asking about a [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Instead of asking about your attempted approach to solve your _real_ problem, explain your _real_ problem. Chances are that there are better C# ways to solve your problem than doing it "C style"... –  Mar 31 '19 at 08:32
  • 1
    Does https://stackoverflow.com/a/5749858/34092 do what you want? – mjwills Mar 31 '19 at 08:40

2 Answers2

6

Apparently you want to reinterpret an array of bytes as an array of shorts.

The easiest way is to use Span:

static void Main(string[] args)
{
    byte[] byteArr = new byte[] { 248, 255, 247, 254 };

    Console.WriteLine(byteArr[2]);
    f(byteArr);
    Console.WriteLine(byteArr[2]);
}

private static void f(byte[] byteArr)
{
    Span<short> shArr = MemoryMarshal.Cast<byte, short>(byteArr);

    shArr[1] = 42;
}   

However the actual question is whether you actually need to do this in the first place.

GSerg
  • 76,472
  • 17
  • 159
  • 346
-1

Use Buffer.BlockCopy

var shArr = new short[byteArr.Length / 2];
Buffer.BlockCopy(byteArr, 0, shArr, 0, byteArr.Length);

https://dotnetfiddle.net/b9ZolZ

shingo
  • 18,436
  • 5
  • 23
  • 42