Re: Problem casting a byte[] to a class
- From: Jon Skeet [C# MVP] <skeet@xxxxxxxxx>
- Date: Mon, 23 Oct 2006 20:17:59 +0100
John J. Hughes II <no@xxxxxxxxxxx> wrote:
Your assuming the data is sequentially stored and no other data exist in the
class, both assumptions are incorrect.
Normally you can serialize your class and desterilized but if the data needs
to be in a compact byte array which I have found need for several times you
will need to parse the data manually. I think you can overload the
serialization function but I have found the below simpler.
Note that for your solution, the line
ms.Capacity = ms.Length;
is unnecessary.
Personally, I'd prefer to create the 6 byte array to start with, and
then populate it. The "standard" BitConverter doesn't have any way to
convert into the middle of an existing array, but my own one does :)
See http://www.pobox.com/~skeet/csharp/miscutil and the
EndianBitConverter class.
In this case, the code might be (converting it to a method rather than
a property);
public byte[] ToArray()
{
EndianBitConverter converter = EndianBitConverter.Little;
byte[] ret = new byte[6];
converter.CopyBytes (val1, ret, 0);
converter.CopyBytes (val2, ret, 2);
converter.CopyBytes (val3, ret, 4);
return ret;
}
--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
.
- Follow-Ups:
- Re: Problem casting a byte[] to a class
- From: John J. Hughes II
- Re: Problem casting a byte[] to a class
- References:
- Problem casting a byte[] to a class
- From: O.B.
- Re: Problem casting a byte[] to a class
- From: John J. Hughes II
- Problem casting a byte[] to a class
- Prev by Date: Re: Problem casting a byte[] to a class
- Next by Date: Re: Problem casting a byte[] to a class
- Previous by thread: Re: Problem casting a byte[] to a class
- Next by thread: Re: Problem casting a byte[] to a class
- Index(es):
Relevant Pages
|