BITSET 
Author Message
 BITSET

Does anybody know where I can find something comparable to the functionality
of the BITSET class in C++ for C?

Thank You
Chad Carroll



Mon, 23 Dec 2002 03:00:00 GMT  
 BITSET


Quote:
>Does anybody know where I can find something comparable to the functionality
>of the BITSET class in C++ for C?

C++ doesn't have a BITSET class, but rather std::bitset.

There is nothing comparable to it in any standard C library. You can represent
a bitset as an array of unsigned char, and then use macros or functions to do
the appropriate array indexing and bit masking arithmetic The number of bits in
an unsigned char is given to you as CHAR_BIT from the header <limits.h>.

The easiest thing is to make the bit array have a fixed size, e.g.

    #include <stdio.h>
    #include <string.h>

    #define BITS_MAX 1024
    #define BITS_ARRAY_MAX = ((BITS_MAX + CHAR_BIT - 1) / CHAR_BIT)

    typedef struct {
        unsigned char bits[BITS_ARRAY_MAX];
    } bitset_t;

    #define bitset_el(BS, BIT) ((BS)->bits[(BIT)/CHAR_BIT])
    #define bitset_mask(BIT) (1U << ((BIT) % CHAR_BIT))

    #define bitset_reset_all(BS) memset((BS)->bits, 0, sizeof (BS)->bits)
    #define bitset_set_all(BS) memset((BS)->bits, UCHAR_MAX, sizeof (BS)->bits)

    #define bitset_set(BS, BIT) (bitset_el(BS, BIT) |= bitset_mask(BIT))
    #define bitset_set(BS, BIT) (bitset_el(BS, BIT) &= ~bitset_mask(BIT))
    #define bitset_isset(BS, BIT) ((bitset_el(BS, BIT) & bitset_mask(BIT)) != 0)

    /* etc */

These macros evaluate the BIT argument more than once; if you aren't
comfortable with that, you need to rewrite these as functions.

If you need the bitset to be variable length, you then need to create a better
abstraction and add to it the logic for dynamic resizing.

It's likely that making the array of unsigned int instead of unsigned char will
provide greater efficiency; but there is no nice trick for discovering the
number of value bits in an unsigned int as a constant expression.

--
#exclude <windows.h>



Mon, 23 Dec 2002 03:00:00 GMT  
 BITSET

Quote:



>> Does anybody know where I can find something comparable to the
>functionality
>> of the BITSET class in C++ for C?

>When you read the C FAQ, how on earth did you miss:
>20.8:   How can I implement sets or arrays of bits?

Dann CHAR_BIT to the rescue! ;)

--
#exclude <windows.h>



Mon, 23 Dec 2002 03:00:00 GMT  
 
 [ 4 post ] 

 Relevant Pages 

1. Bitset examples from the FAQ (unsigned char?)

2. libclc bitset import/export

3. libclc: bitset interface, new final vote

4. libclc: bitset interface

5. Help in finding the bitsets?

6. C++ to C# std::bitset

7. bitsets

8. bitset

9. bitset?

10. template-Klasse bitset

11. use bitset instead

12. Compiler Error C2783 when using Bitsets.

 

 
Powered by phpBB® Forum Software