How to cast a dword into a byte array in C#
Question
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
- packetbuffer[0] will be 0xC
- packetbuffer[1] will be 0x00
- packetbuffer[2] will be 0x50
- 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];
Solution
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
.
OTHER TIPS
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)