I need to create a very large array of bits / booleans. How do I do this in C / C ++?

Is it possible to create an array of bits with more than 100000000 elements? If so, how do I do this? I know that for a char array I can do this:

char* array;

array = (char*)malloc(100000000 * sizeof(char));

If I were to declare an array char array[100000000], I would get a segmentation error, since the maximum number of elements was exceeded, so I use malloc.

Is there something similar for a bit array?

+3
source share
9 answers

If you use C ++, std::vector<bool>specializes in packing elements into a bitmap. Of course, if you use C ++, you need to stop using it malloc.

+12

boost:: dynamic_bitset. - ( Boost):

boost::dynamic_bitset<> x(100000000); // all 0 by default
x[0] = 1;
x[1] = 1;
x[4] = 1;

, 32 4 , .

+8

C ++ char - . . , , , - ( ):

unsigned *array;
array = (unsigned *) malloc(100000000 / sizeof(unsigned) + 1);

/* Retrieves the value in bit i */
#define GET_BIT(array, i) (array[i / sizeof(unsigned)] & (1 << (i % sizeof(unsigned))))

/* Sets bit i to true*/
#define SET_BIT(array, i) (array[i / sizeof(unsigned)] |= (1 << (i % sizeof(unsigned))))

/* Sets bit i to false */
#define CLEAR_BIT(array, i) (array[i / sizeof(unsigned)] &= ~(1 << (i % sizeof(unsigned))))
+5

- . , 12,5 (100 ), 100 (100 ) ~ 4 . , 12 100 - . , , .

+4

STL, std::bitset.

( 100 000 000 100000000/32 unsigned int, 32 .)

std::vector<bool>, , .

+2

++.

, STL, std::bitset.

std::bitset<100000000> array

, , std::vector<bool> boost::dynamic_bitset, http://en.cppreference.com/w/cpp/utility/bitset (. )

+1

, !

- char!

, 8 char!

"" 12'500'000 !

: http://www.somacon.com/p125.php

google:)

0

:

unsigned char * array;
array = (unsigned char *) malloc ( 100000000 / sizeof(unsigned char) + 1);

bool MapBit ( unsigned char arraybit[], DWORD position, bool set)
{
    //work for 0 at 4294967295 bit position
    //calc bit position
    DWORD bytepos = ( position / 8 );
    //
    unsigned char bitpos =  ( position % 8);

    unsigned char bit = 0x01;

    //get bit
    if ( bitpos )
    {
        bit = bit << bitpos;
    }

    if ( set )
    {
        arraybit [ bytepos ] |= bit;
    }
    else
    {
        //get
        if ( arraybit [ bytepos ] & bit )
            return true;
    }

    return false;
}
0

I like bitarray in the open source fxt library at http://www.jjj.de/fxt/ . It is simple, efficient, and contained in several headers, so it’s easy to add to your project. In addition, there are many additional features to use with bitarray (see http://www.jjj.de/bitwizardry/bitwizardrypage.html ).

0
source

Source: https://habr.com/ru/post/1738798/


All Articles