1

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?

4
  • Do you have a more specific example we can help you with and which you can use as a "template" on how to deal with this in general? Commented May 15, 2023 at 17:52
  • 1
    Can't you create a struct which matches the memory layout of that byte array. Something like; stackoverflow.com/questions/2871/… Commented May 15, 2023 at 17:55
  • @rene. That might work, I am not overly familiar with struct layout in c#, but looking at the example, it seems that it would work. The FieldOffset attribute is the BIT position, yes? It looks i should be able to assign each property directly. However for those values that only take < 8 bits, the smallest property data type would be a byte. Would that cross byte boundaries? IE. byte value1=0b011. It should only take 3 bits, 0x07 as it max value. But if the user enters 10, would it cross into the boundary of the next date type? Commented May 15, 2023 at 18:26
  • FieldOffset is byte so you would still need to fiddle with masks for some setters and getters on your struct. See also: learn.microsoft.com/en-us/dotnet/api/… Commented May 15, 2023 at 18:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.