Page 1 of 1

bool vs bit array

Posted: Sat Nov 25, 2006 7:47 am
by Neo
I have a scenario where I need to store the state of 64 entities (max).
I could do this with either a bool array or a 64bit variable (where I use 1 bit to represent each entity).

Option1

Code: Select all

bool state[64];
Option2

Code: Select all

UINT64 state;
//use shifts to determine individual entities
I was wondering which would be more efficient/faster.
Any ideas on this?

Posted: Sat Nov 25, 2006 9:16 am
by Tyler
Clearly bool would be faster because it is a build in system for handling which only requires a single check. The second option is far ore efficient though as it only takes up 8 bytes... whereas bool if i remember correctly uses a whole byte meaning you save 56 bytes.

Posted: Sat Nov 25, 2006 11:00 am
by earlz
not sure if it works but might you try

Code: Select all

char _64bits[64]:1;
not sure if it works though..

edit:
ok.. tried to do that so my best idea is to do something like

Code: Select all

typedef struct{
    unsigned char bit0:1;
    unsigned char bit1:1;
    unsigned char bit2:1;
    unsigned char bit3:1;
    unsigned char bit4:1;
    unsigned char bit5:1;
    unsigned char bit6:1;
    unsigned char bit7:1;
}__attribute__((packed))_8bits;

_8bits _64bits[8];
but thats the only fast, easy, and effiecent way...

Re: bool vs bit array

Posted: Sat Nov 25, 2006 10:51 pm
by Brendan
Hi,
Neo wrote:I was wondering which would be more efficient/faster.
Any ideas on this?
I'd be tempted to use a 64-bit unsigned int and inline assembly (defined as a macro) based on the "BT" instruction.


Cheers,

Brendan

Posted: Thu Nov 30, 2006 7:04 am
by Solar
Hmmmm...

Is this C99? Or C++? (Because you use bool, which doesn't exist in C89.) Userspace, I assume - or kernel work?

For userspace C++ (or if your kernel-space library includes it), you could take a look at <bitset>... depending on what you want to do with those flags, that might be more conventient / efficient.

Don't use vector<bool>, though. It's broken. (Because operator[] doesn't return a pointer to an element, it isn't really a vector, or a STL container at that, so the whole abstraction is broken. You might want deque<bool>, but <bitset> is optimized for bool.)

Posted: Fri Dec 01, 2006 6:02 am
by Neo
Solar wrote:Hmmmm...

Is this C99? Or C++? (Because you use bool, which doesn't exist in C89.) Userspace, I assume - or kernel work?
C++, userspace

Re: bool vs bit array

Posted: Fri Dec 01, 2006 6:11 pm
by B.E
Neo wrote: I was wondering which would be more efficient/faster.
Any ideas on this?
You have to deside on which is more applicable to the problem. Here's some factors that you need to consider:
  • The array is faster then the 64-bit UINT, if you are using it for single bool manipulation. but is slower when using it for multiple bool manipulation.

    Using the array procedures more readable code then the 64-bit UINT.

    the integer is a lot harder to upgrade.
The choice is yours