Search code examples
c++bit-manipulationbitbitsetmemory-efficient

How can I have exactly 2 bits in memory?


I should be able to store a value in a data structure that could go from 0 to 3.. so I need 2 bits. This data structure I will be great 2 ^ 16 locations. So, i want to have 2 ^ 16 * 2 (bits). In C + + do you use to have exactly 2 bits in memory?


Solution

  • You need two bits per unit (not three), so you can pack four units into one byte, or 16 units into one 32-bit integer.

    So you will need a std::array<uint32_t, 4096> to accomodate 216 units of 2-bit values.

    You access the nth value as follows:

    unsigned int get(std::size_t n, std::array<uint32_t, 4096> const & arr)
    {
        const uint32_t u = arr[n / 16];
        return (u >> (2 * (n % 16))) & 0x3;
    }
    

    Alternatively, you could go with a bitfield:

    struct BF32 {
      uint32_t u0 : 2;
      uint32_t u1 : 2;
      //...
      uint32_t uF : 2;
    }
    

    And then make an std::array<BF32, 4096>.