31

I am curious to know, Is it possible to use array of bit fields? Like:

struct st
{
  unsigned int i[5]: 4;
}; 
msc
  • 33,420
  • 29
  • 119
  • 214
  • 3
    Notice that most *recent* C code don't use bit fields anymore. A useful alternative would be to use bitmask fields, and do bitwise operations on them. BTW, the compiler generates equivalent code. – Basile Starynkevitch Jan 29 '17 at 07:39
  • 6
    @BasileStarynkevitch: I wonder where you derive this from. Using bit-fields is much less error prone than handling bitmask fields with bitwise operations. – chqrlie Feb 04 '17 at 22:22

4 Answers4

27

No, you can't. Bit field can only be used with integral type variables.

C11-§6.7.2.1/5

A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type.

Alternatively you can do this

struct st
{
    unsigned int i: 4;  
} arr_st[5]; 

but its size will be 5 times the size of a struct (as mentioned in comment by @Jonathan Leffler) having 5 members each with bit field 4. So, it doesn't make much sense here.

More closely you can do this

struct st
{
    uint8_t i: 4;   // Will take only a byte
} arr_st[5]; 
Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
  • 8
    But the size of that (`struct st { unsigned int i: 4; } arr_st[5];` would, most likely, be 5 times the size of an `unsigned int`; it would not be 20 bits long. – Jonathan Leffler Jan 29 '17 at 07:10
  • @JonathanLeffler; Yeah. But no other ways to declare an array of bit fields. – haccks Jan 29 '17 at 07:22
  • @haccks Thanks for helping me. – msc Jan 29 '17 at 07:55
  • type `uint8_t` might not be available. `struct st { unsigned char i: 4; } arr_st[5];` or just `unsigned char arr[5];` seem preferable. – chqrlie Jan 29 '17 at 08:13
  • 1
    @IlmariKaronen; I mean to say struct `arr_st` will be `5` times of struct like `struct stt { unsigned int i: 4; unsigned int j: 4; unsigned int k: 4; unsigned int l: 4; unsigned int m: 4; } s;` – haccks Jan 29 '17 at 13:53
10

C does not support arrays of bit-fields, so the short answer is no.

For very large arrays, it might be worthwhile to pack values, 2 per byte, this way:

#define ARRAY_SIZE  1000000

unsigned char arr[(ARRAY_SIZE + 1) / 2];

int get_4bits(const unsigned char *arr, size_t index) {
    return arr[index >> 1] >> ((index & 1) << 2);
}

int set_4bits(unsigned char *arr, size_t index, int value) {
    arr[index >> 1] &= ~ 0x0F << ((index & 1) << 2);
    arr[index >> 1] |= (value & 0x0F) << ((index & 1) << 2);
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
7

You can write your own class for this case. For example:

template <typename T, size_t ITEM_BIT_SIZE>
class BitArrayView {
private:
    static const size_t ARRAY_ENTRY_BITS = sizeof(T) * 8;
    static const T ITEM_MASK = (~((T) 0)) >> (ARRAY_ENTRY_BITS - ITEM_BIT_SIZE);
    T* arr;
public:
    struct ItemMutator {
        BitArrayView* owner;
        size_t index;
        T operator=(T value) {
            return owner->set(index, value);
        }
        operator T() {
            return owner->get(index);
        }
    };
    const size_t bitSize;
    BitArrayView(T* arr, size_t length) : arr(arr), bitSize((length * ARRAY_ENTRY_BITS) / ITEM_BIT_SIZE) {}
    T get(size_t index) const {
        size_t bitPos = index * ITEM_BIT_SIZE;
        size_t arrIndex = bitPos / ARRAY_ENTRY_BITS;
        size_t shiftCount = bitPos % ARRAY_ENTRY_BITS;
        return (arr[arrIndex] >> shiftCount) & ITEM_MASK;
    }
    T set(size_t index, T value) {
        size_t bitPos = index * ITEM_BIT_SIZE;
        size_t arrIndex = bitPos / ARRAY_ENTRY_BITS;
        size_t shiftCount = bitPos % ARRAY_ENTRY_BITS;
        value &= ITEM_MASK; // trim
        arr[arrIndex] &= ~(ITEM_MASK << shiftCount); // clear target bits
        arr[arrIndex] |= value << shiftCount; // insert new bits 
        return value;
    }
    ItemMutator operator[](size_t index) {
        return { this, index };
    }
};

And then you may access it like a "bit field" array:

// create array of some uints
unsigned int arr[5] = { 0, 0, 0, 0, 0 };

// set BitArrayView of 3-bit entries on some part of the array 
// (two indexes starting at 1)
BitArrayView<unsigned int, 3> arrView(arr + 1, 2);

// should equal 21 now => (2 * 32) / 3
arrView.bitSize == 21;

for (unsigned int i = 0; i < arrView.bitSize; i++) {
    arrView[i] = 7; // eg.: 0b111;
}

// now arr[1] should have all bits set
// and arr[2] should have all bits set but last one unset => (2 * 32) % 3 = 1
// the remaining arr items should stay untouched

This is simple implementation which should work with unsigned backing arrays only.

Notice "the mutator trick" in operator[] ;).

Of course some other operators could be implemented, too.

EDIT (After Josh Klodnicki's comment)

It actually contained a bug, which appeared when "bit chunks" overlapped partially actual array entries. Here's a fix (but it is kind of ugly ;) ).

template <typename T, size_t ITEM_BIT_SIZE>
class BitArrayView {
private:
    static const size_t ARRAY_ENTRY_BITS = sizeof(T) * 8;
    T* arr;

public:
    struct ItemMutator {
        BitArrayView* owner;
        size_t index;
        ItemMutator& operator=(T value) {
            owner->set(index, value);
            return *this;
        }
        operator T() {
            return owner->get(index);
        }
    };

    const size_t bitSize;
    BitArrayView(T* arr, size_t length) : arr(arr), bitSize((length* ARRAY_ENTRY_BITS) / ITEM_BIT_SIZE) {}

    T get(size_t index) const {
        T value = 0;
        int pos = 0;
        size_t bitPos = index * ITEM_BIT_SIZE;
        size_t arrIndex = bitPos / ARRAY_ENTRY_BITS;
        size_t readPos = bitPos % ARRAY_ENTRY_BITS;
        size_t bitCount = ITEM_BIT_SIZE;
        if (readPos > 0) {
            int chunkLength = ARRAY_ENTRY_BITS - readPos;
            if (bitCount < chunkLength) {
                value = (((arr[arrIndex] >> readPos) & ((1u << bitCount) - 1)));
                readPos += bitCount;
                return value;
            }
            value = (((arr[arrIndex] >> readPos) & ((1u << chunkLength) - 1)));
            ++arrIndex;
            readPos = 0;
            pos = chunkLength;
            bitCount -= chunkLength;
        }
        while (bitCount >= ARRAY_ENTRY_BITS) {
            value |= (arr[arrIndex++] << pos);
            pos += ARRAY_ENTRY_BITS;
            bitCount -= ARRAY_ENTRY_BITS;
        }
        if (bitCount > 0) {
            value |= ((arr[arrIndex] & ((1u << bitCount) - 1)) << pos);
        }
        return value;
    }

    void set(size_t index, T value) {
        size_t bitPos = index * ITEM_BIT_SIZE;
        size_t arrIndex = bitPos / ARRAY_ENTRY_BITS;
        size_t writePos = bitPos % ARRAY_ENTRY_BITS;
        size_t bitCount = ITEM_BIT_SIZE;

        if (writePos > 0) {
            int chunkLength = ARRAY_ENTRY_BITS - writePos;
            if (bitCount < chunkLength) {
                auto mask = (((1u << bitCount) - 1) << writePos);
                arr[arrIndex] = (arr[arrIndex] ^ ((arr[arrIndex] ^ (value << writePos)) & mask));
                writePos += bitCount;
                return;
            }
            auto mask = (((1u << chunkLength) - 1) << writePos);
            arr[arrIndex] = (arr[arrIndex] ^ ((arr[arrIndex] ^ (value << writePos)) & mask));
            ++arrIndex;
            writePos = 0;
            value >>= chunkLength;
            bitCount -= chunkLength;
        }
        while (bitCount >= ARRAY_ENTRY_BITS) {
            arr[arrIndex++] = value;
            value >>= ARRAY_ENTRY_BITS;
            bitCount -= ARRAY_ENTRY_BITS;
        }
        if (bitCount > 0) {
            auto mask = ((1u << bitCount) - 1);
            arr[arrIndex] = (arr[arrIndex] ^ ((arr[arrIndex] ^ value) & mask));
        }
    }

    ItemMutator operator[](size_t index) {
        return { this, index };
    }
};

As it is now not simple any more, below I put a simple implementation of Bit Array which access single bit separately.

template<size_t SIZE>
class BitArray {
private:
    static constexpr const size_t CELL_SIZE = sizeof(unsigned) * 8;
    static constexpr const size_t ARR_SIZE = (SIZE + CELL_SIZE) / CELL_SIZE;
    unsigned arr[ARR_SIZE];
public:
    class BitMutator {
    private:
        unsigned& cellRef;
        const size_t bitPos;

    public:
        BitMutator(unsigned& cellRef, size_t bitPos) : cellRef(cellRef), bitPos(bitPos) {}
        BitMutator(const BitMutator& source) = default;
        BitMutator(BitMutator&& source) = default;

        BitMutator& operator=(unsigned value) {
            cellRef &= ~(1u << bitPos);
            cellRef |= ((value & 1u) << bitPos);
            return *this;
        }
        operator unsigned() const {
            return (cellRef >> bitPos) & 1u;
        }
    };

    BitArray() : arr{0} {};

    BitMutator operator[](size_t index) {
        return BitMutator(arr[index / CELL_SIZE], index % CELL_SIZE);
    }

    size_t size() const {
        return SIZE;
    }

    size_t arr_size() const {
        return ARR_SIZE;
    }

    operator unsigned* () {
        return arr;
    }
};

void testBitArray() {
    BitArray<21> bitArr;

    for (int i = 0; i < bitArr.size(); i++) {
        bitArr[i] = i % 2;
    }

    for (int i = 0; i < bitArr.size(); i++) {
        std::cout << bitArr[i] << ", ";
    }

    unsigned* backing_array = (unsigned*) bitArr;
    size_t backing_arr_size = bitArr.arr_size();

    for (int i = 0; i < backing_arr_size; i++) {
        std::cout << backing_array[i] << ", ";
    }
} 
Tomasz Gawel
  • 8,379
  • 4
  • 36
  • 61
  • This implementation does not account for "fields" that overlap array entries. In the example, `arrView[10]` should access `arr[1]{30-31}` _and_ `arr[2]{0}`, but as written it does not. – Josh Klodnicki May 02 '23 at 16:56
  • 1
    @JoshKlodnicki you're right, I'll fix it and edit the answer. – Tomasz Gawel May 02 '23 at 20:26
  • @JoshKlodnicki I provided a fixed version, and a simple BItArray implementation as well (as the original BitArrayView occured to appear overcomplicated after my changes). – Tomasz Gawel May 04 '23 at 13:44
0

No, bitfields only support integral types. But for very small arrays, you can store each element as a property individually, for example:

struct st
{
  unsigned int i0: 1;
  unsigned int i1: 1;
  unsigned int i2: 1;
  unsigned int i3: 1;
  unsigned int i4: 1;
};

The disadvantage of this approach is obviously that you can no longer use array-based operations or methods, such as run-time indexing, but it works well enough for basic applications like mathematical vectors.

Nirvana
  • 405
  • 3
  • 15