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

假如想象 提交于 2019-12-11 06:55:39

问题


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


回答1:


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);



回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/5831916/reading-from-writing-to-byte-arrays-in-c-sharp-net-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!