# Array of boolean

• 10-23-2001
DMaxJ
Array of boolean
void main()
{
boolean number[8] ;

}

is this the proper way to declare an array of boolean characters?

Thanks
• 10-23-2001
Procyon
Yes, except it's normally written as bool, not boolean.
• 10-23-2001
Unregistered
Arrays of bools are horibly inefficient. Use bitpacking instead. Each bool is a byte, while a byte can be used to store 8 boolean values as bits. That's a size savings of 8:1!
• 10-24-2001
electricglidingman
hey, could you please briefly (or not) explain how to do the bitpacking thing?
• 10-24-2001
Magos
unsigned char Number;

(Number & 1) Get 1:st bit out of Number
(Number & 2) Get 2:nd bit out of Number
(Number & 4) Get 3:rd bit out of Number
(Number & 8) Get 4:th bit out of Number
(Number & 16) Get 5:th bit out of Number
(Number & 32) Get 6:th bit out of Number
(Number & 64) Get 7:th bit out of Number
(Number & 128) Get 8:th bit out of Number

Ex:
if(Number & 1) cout << "First bit is true";
if(!(Number & 4)) cout << "Third bit is false";
• 10-24-2001
gliptic
Setting a bit:

(Number | 1) Set 1:st bit in Number
(Number | 2) Set 2:nd bit in Number
(Number | 4) Set 3:rd bit in Number
(Number | 8) Set 4:th bit in Number
(Number | 16) Set 5:th bit in Number
(Number | 32) Set 6:th bit in Number
(Number | 64) Set 7:th bit in Number
(Number | 128) Set 8:th bit in Number

Toggle a bit:

(Number ^ 1) Toggle 1:st bit in Number
(Number ^ 2) Toggle 2:nd bit in Number
(Number ^ 4) Toggle 3:rd bit in Number
(Number ^ 8) Toggle 4:th bit in Number
(Number ^ 16) Toggle 5:th bit in Number
(Number ^ 32) Toggle 6:th bit in Number
(Number ^ 64) Toggle 7:th bit in Number
(Number ^ 128) Toggle 8:th bit in Number

In assembler, you can do much more efficient bitpacking but I guess most of you don't care about assembler (C++ board).
• 10-24-2001
Aran
umm.. how would you declare that and use it? I'm looking to use a similar idea for a project for school...

would it be like

Code:

```main() {  int a;    // sets first to true  a ^ 1  // all the rest are false still  if (a | 1)  printf("a is true");  else  printf("a is false"); }```
• 10-25-2001
gliptic
No, the '^' is XOR. It toggles bits so you must use '|' to set it and you must write:

a ^= 1;

and not just 'a ^ 1' because that is removed by your compiler because it doesn't do anything.

The rest of the bits in 'a' can be anything. You have to initialize it to 0 to be sure it is 0.

This loop sets all the bits in a byte:
Code:

```unsigned char a; long b = 1; //The lowest bit is set for(long i = 0; i < 8; i++) {  a |= b; //Set the bit  b <<= 1; //Go to the next bit }```
• 10-25-2001
Magos
Wow
Wow! I have never seen the 'b<<=1' operator before. Cool! :cool: Multiplies with 2, right?
• 10-25-2001
gliptic
Yes, it's the same as moving all bits to left one step.

(00001 << 1) = 00010

In that way I can set all the bits in the byte.
• 10-25-2001
Nick
Well
0x00000001 XOR 0x000000001 is 0x00000000