Unsafe conversion to given pointer in buffer

Viewed 131

I am trying to figure out how to get this method to start at a index being ptr instead of overwriting from 0 - 8 bytes. Also if anyone knows how to make this work with Big / Little edian machines due to being networked, that would be awesome.

private byte[] buffer = new byte[30];
private int ptr = 0;

unsafe void GetBytes(ulong value)
{
    fixed (byte* b = buffer) //start at buffer[ptr]
        *((int*)b) = *(int*)&value;

    ptr += 8;
}

I figured out how to make a pointer to the ptr via the following

private byte[] buffer = new byte[30];
private int ptr = 0;

unsafe void GetBytes(ulong value)
{
    fixed (byte* b = &buffer[ptr]) //start at buffer[ptr]
        *((int*)b) = *(int*)&value;

    ptr += 8;
}
1 Answers

You can convert endianness easily:

using System.Buffers.Binary;

if (!BitConverter.IsLittleEndian)
{
    value = BinaryPrimitives.ReverseEndianness(value);
}

I would prefer to use Span which will be safer and easier to read:

using System.Buffers.Binary;

Span<byte> span = buffer;
BinaryPrimitives.WriteUInt64LittleEndian(span.Slice(ptr), value);

If you want to use your system's endianness rather than something explicit, you can do that too:

using System.Runtime.InteropServices;

Span<byte> span = buffer;
MemoryMarshal.Write(span.Slice(ptr), value);

Edit for non-Core:

You can use HostToNetworkOrder to convert integers to big endian prior to writing to your pointer.

Related