Reading from/Writing to Byte Arrays in C# .net 4
Greetings Overflowers,
I love the flexibility of memory mapped files in that you can read/write any v开发者_如何学运维alue type.
Is there a way to do the same with byte arrays without having to copy them into for e.g. a memory map buffers ?Regards
You can use the BitConverter
class to convert between base data types and byte arrays.
You can read values directly from the array:
int value = BitConverter.ToInt32(data, pos);
To write data you convert it to a byte array, and copy it into the data:
BitConverter.GetBytes(value).CopyTo(data, pos);
You can bind a MemoryStream
to a given byte array, set it's property Position
to go to a specific position within the array, and then use a BinaryReader
or BinaryWriter
to read / write values of different types from/to it.
You are searching the MemoryStream
class which can be initialised (without copying!) from a fixed-size byte array.
(Using unsafe code) The following sample shows how to fill a 16 byte array with two long values, which is something BitConverter still can't do without an additional copy operation:
byte[] bar = new byte[16];
long lValue1 = 1;
long lValue2 = 2;
unsafe {
fixed (byte* bptr = &bar[0]) {
long* lptr = (long*)bptr;
*lptr = lValue1;
// pointer arithmetic: for a long* pointer '+1' adds 8 bytes.
*(lptr + 1) = lValue2;
}
}
Or you could make your own StoreBytes() method:
// here the dest offset is in bytes
public static void StoreBytes(long lValue, byte[] dest, int iDestOffset) {
unsafe {
fixed (byte* bptr = &dest[iDestOffset]) {
long* lptr = (long*)bptr;
*lptr = lValue;
}
}
}
Reading values from a byte array is no problem with BitConverter since you can specify the offset in .ToInt64.
Alternative : use Buffer.BlockCopy, which can convert between array types.
精彩评论