I would suggest that your best bet, if speed isn't critical, would probably be to have the data stored in a byte[]
, and have a class which holds an immutable reference to that byte[]
and has properties whose get/set methods access the array. Property gets/sets would always reflect and be reflected in the state of the array, since the array itself would hold the state of the object. No "unsafe" code required.
Methods would probably look something like:
public static class IntPack
{ // All methods ssume unchecked arithmetic
public static Int16 FetchI16LE(this byte[] dat, int offset)
{
return (Int16)(dat[offset] + (dat[offset + 1] << 8));
}
public static Int32 FetchI32LE(this byte[] dat, int offset)
{
return dat[offset] + (dat[offset + 1] << 8) +
(dat[offset + 2] << 16) + (dat[offset + 3] << 24);
}
public static void StuffI16LE(this byte[] dat, int offset, int value)
{
dat[offset] = (byte)(value);
dat[offset+1] = (byte)(value >> 8);
}
public static void StuffI32LE(this byte[] dat, int offset, int value)
{
dat[offset] = (byte)(value);
dat[offset + 1] = (byte)(value >> 8);
dat[offset + 2] = (byte)(value >> 16);
dat[offset + 3] = (byte)(value >> 24);
}
}
The methods indicated assume little-endian ordering. One could easily write corresponding __BE methods methods for big-endian.