How to get array of bits in a structure?

前端 未结 6 2208
走了就别回头了
走了就别回头了 2020-12-14 01:00

I was pondering (and therefore am looking for a way to learn this, and not a better solution) if it is possible to get an array of bits in a structure.

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-14 02:02

    C++ would use std::vector or std::bitset.

    In C, to emulate std::vector semantics, you use a struct like this:

    struct Bits {
        Word word[];
        size_t word_count;
    };
    

    where Word is an implementation-defined type equal in width to the data bus of the CPU; wordsize, as used later on, is equal to the width of the data bus.

    E.g. Word is uint32_fast_t for 32-bit machines, uint64_fast_t for 64-bit machines; wordsize is 32 for 32-bit machines, and 64 for 64-bit machines.

    You use functions/macros to set/clear bits.

    To extract a bit, use GET_BIT(bits, bit) (((bits)->)word[(bit)/wordsize] & (1 << ((bit) % wordsize))).

    To set a bit, use SET_BIT(bits, bit) (((bits)->)word[(bit)/wordsize] |= (1 << ((bit) % wordsize))).

    To clear a bit, use CLEAR_BIT(bits, bit) (((bits)->)word[(bit)/wordsize] &= ~(1 << ((bit) % wordsize))).

    To flip a bit, use FLIP_BIT(bits, bit) (((bits)->)word[(bit)/wordsize] ^= (1 << ((bit) % wordsize))).

    To add resizeability as per std::vector, make a resize function which calls realloc on Bits.word and changes Bits.word_count accordingly. The exact details of this is left as a problem.

    The same applies for proper range-checking of bit indices.

提交回复
热议问题