views:

2000

answers:

2

Hello,

As you already may know,I'm migrating into C# and some things in C++ look different.

C++ code

    BYTE packetBuffer[32] = {0};
 *(LPWORD)(packetBuffer + 0) = 0xC;
 *(LPWORD)(packetBuffer + 2) = 0x5000;
 *(LPDWORD)(packetBuffer + 6) = dwArgs[13];
 *(LPDWORD)(packetBuffer + 10) = *(keyArray2 + 0);
 *(LPDWORD)(packetBuffer + 14) = *(keyArray2 + 1);

Note dwArgs and keyArray2 are "array of DWORD"

This is how it's placed

  1. packetbuffer[0] will be 0xC
  2. packetbuffer[1] will be 0x00
  3. packetbuffer[2] will be 0x50
  4. packetbuffer[3] will be 0x00

and so on

How to do that in C#?

I tried this,but it doesn't work

packetBuffer[0] = 0xC;
packetBuffer[2] = (byte)0x5000; //error
packetBuffer[6] = (byte)dwArgs[13];
+2  A: 

You can use BitConverter to convert data to and from byte arrays. Unfortunately there's no facility to copy into an existing array. My own EndianBitConverter in my MiscUtil library allows this if you need it, as well as allowing you to specify the endianness to use of course. (BitConverter is usually little endian in .NET - you can check it with the IsLittleEndian field.)

For example:

EndianBitConverter converter = EndianBitConverter.Little;
converter.CopyBytes((short) 0xc, packetBuffer, 0);
converter.CopyBytes((int) 0x5000, packetBuffer, 2);
converter.CopyBytes(dwArgs[13], packetBuffer, 6);

etc. The cast to int in the second call to CopyBytes is redundant, but included for clarity (bearing in mind the previous line!).

EDIT: Another alternative if you'd rather stick with the .NET standard libraries, you might want to use BinaryWriter with a MemoryStream.

Jon Skeet
@Jon Skeet,Thanks! Could you check your library if it allows you to do this job).Also an example of how it works will be highly appreciated.
John
@John: I was editing while you were commenting :)
Jon Skeet
A: 

You can't. C# is strongly typed. A variable has one, and only one type. Trickery like the C++ reinterpret_cast is not allowed.

There are several approaches to your problem though. The first, and obvious, is to use the built-in serialization framework. Don't bother writing your own serialization code unless you have to. And in .NET, you don't often have to.

The second is to use the BitConverter class (the GetBytes method should do the trick for converting to byte array)

jalf
Strongly typed doesn't mean you can't fiddle with the bits and bytes in a primitive value type like the integral ones. The strongest restriction in the CLR typing system is casting between reference types.
Cecil Has a Name