Reading from/Writing to Byte Arrays in C# .net 4

2019-07-31 17:18发布

Greetings Overflowers,

I love the flexibility of memory mapped files in that you can read/write any value 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

4条回答
我想做一个坏孩纸
2楼-- · 2019-07-31 17:52

(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.

查看更多
姐就是有狂的资本
3楼-- · 2019-07-31 17:56

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);
查看更多
家丑人穷心不美
4楼-- · 2019-07-31 17:58

You are searching the MemoryStream class which can be initialised (without copying!) from a fixed-size byte array.

查看更多
够拽才男人
5楼-- · 2019-07-31 18:00

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.

查看更多
登录 后发表回答