Inserting different type of values into a Bitarray

57 views Asked by At

I have a bit array that represents a data protocol, 1024 bytes. The range of the fields go from very small, to int32s in size. For example, ProtoID = bits 0-3, Source = bits 4-6, Value1 = bits 7-14, value2 = Bit2

Something like

BitArray.SetValue(int value, startIndex, maxBitstoSet) //Or maybe i can make it a generic insert byte[] and use BitConverter.GetBytes(value)? //The maxbits to set is to isolate just those bits, so they don't cross boundaries of another field in case the user enters a value that is more than it can old.

I am struggling on the way to implement this. Would i need to create a mask based on the value data type ( or based on the lenght of the byte[]) and just OR them to set those bits?

EDIT: Someone suggested a custom struct might work, something like this:

[StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]
public struct NewStuff
{
    [MarshalAs(UnmanagedType.U1)]
    [FieldOffset(0)]
    public byte ProtoID = 0b011;

    [MarshalAs(UnmanagedType.U1)]
    [FieldOffset(3)]
    public byte value1;

    [MarshalAs(UnmanagedType.U1)]
    [FieldOffset(7)]
    public byte value2;

}

Value1 is can only be 3 bits only, so the max should be 0x07. But what if the user enters 0x08, that would cross bit boundaries and overwrite value2 LSB?

0

There are 0 answers