Come lanciare un dword in un array di byte in C #
Domanda
Come già saprete, sto migrando in C # e alcune cose in C ++ un aspetto diverso.
codice C ++
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);
dwArgs nota e keyArray2 sono "serie di DWORD"
Questo è come è collocato
- packetbuffer [0] sarà 0xC
- packetbuffer [1] sarà 0x00
- packetbuffer [2] sarà 0x50
- packetbuffer [3] sarà 0x00
e così via
Come farlo in C #?
Ho provato a farlo, ma non funziona
packetBuffer[0] = 0xC;
packetBuffer[2] = (byte)0x5000; //error
packetBuffer[6] = (byte)dwArgs[13];
Soluzione
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
.
Altri suggerimenti
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)