0

I have to create a structure which will have a size of 2 bytes. The structure have to contain 4 values and every value should have 4-bits length. How can I do that?

In C I can do something like:

typedef struct MyStructure
{
    uint8_t  value1   :4;
    uint8_t  value2   :4;
    uint8_t  value3   :8;
}
szaman
  • 6,666
  • 13
  • 53
  • 81

4 Answers4

2

Because the smallest addressable size of value is byte (8 bits) you can't do that so easily. You can create a type with two byte fields and use properties to get/set them as 4 different values.

public struct MyStruct
{
    private byte _ab;
    private byte _cd;

    public byte A
    {
        get { return (byte)(_ab & 15); }
        set { _ab = (byte)((_ab & 240) | (value & 15)); }
    }

    public byte B
    {
        get { return (byte)(_ab >> 4); }
        set { _ab = (byte)((_ab & 15) | (value & 240)); }
    }

    // the same for C and D
}
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1

Unless there's already some class for this purpose I'm unaware of, your best bet is probably to use a UInt16, as suggested by leppie, then have properties to get and set the "sub-values", transparently performing masking and shifting as needed.

BambooleanLogic
  • 7,530
  • 3
  • 30
  • 56
1

You can specify two bytes and use properties for the bit access

public struct X {
    public byte A;
    public byte B;

    public byte A_L {
        get {
            return (byte)(A >> 4);
        }
    }
    public byte A_R {
        get {
            return (byte)(A & 15);
        }
    }
    public byte B_L {
        get {
            return (byte)(B >> 4);
        }
    }
    public byte B_R {
        get {
            return (byte)(B & 15);
        }
    }
}
Deathspike
  • 8,582
  • 6
  • 44
  • 82
0

You may use standard UInt16 type (no explicit structures at all):

  UInt16 value = ...

  // Get corresponding values:

  Byte value1 = (Byte) (value >> 12);
  Byte value2 = (Byte) ((value >> 8) & 0xF);
  Byte value3 = (Byte) (value & 0xF);

  // Set corresponding values

  UInt16 value = (UInt16) ((value1 << 12) | (value & 0x0FFF));
  UInt16 value = (UInt16) ((value2 << 8) | (value & 0xF0FF));
  UInt16 value = (UInt16) (value3 | (value & 0xFF00));
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Won't the size of this be > 2 bytes? – szaman Sep 04 '13 at 07:39
  • 1
    The structure in the question is of 2 byte size, so I've chosen UInt16 as its representation. You can use int/uint (4 bytes), long/ulong (8 bytes) for "value", just change 1st line to "Byte value1 = (Byte) ((value >> 12) & 0xFF);" – Dmitry Bychenko Sep 04 '13 at 07:48