Continue to Site

# [AVR]problem with array of bits

Status
Not open for further replies.

#### engallam

##### Junior Member level 1
hi everybody
I have a problem in define array of bits in "mikroc pro for avr"

like
Code:
bit x[2][5]= {{1,0,1,0,0},{1,1,1,0,1}};

Code:
int x[2][5]= {{1,0,1,0,0},{1,1,1,0,1}};
to save more memory

how can i do this
thanks a lot

Last edited by a moderator:

Ask mikroE support whether bit array can be defined or not in mikroC PRO. I think its not possible.

Why don´t you use the struct command to do that ?

bigdogguru

### bigdogguru

Points: 2
struct or union can be used for this purpose, eg
Code:
union{
unsigned x;
struct {
unsigned bit0:1;
unsigned bit1:1;
unsigned bit2:1;
unsigned bit3:1;
unsigned bit4:1;
unsigned bit5:1;
unsigned bit6:1;
...
};
} a;

or
bitwise logical and,or,not can be used also
Code:
#define MAXBITS        80
unsigned char *mem = malloc((MAXBITS + 7)/8);
if(pos<MAXBITS){
register unsigned char mask = 1 << (pos % 8);
return (mem[pos/8] & mask) ? 1 : 0;
}
return -1;
}
int setbit(int pos, int val){
if(pos<MAXBITS){
register unsigned char mask = 1 << (pos % 8);
if(val)
else
return val;
}
return -1;
}

bigdogguru

### bigdogguru

Points: 2
If your goal is to create a defined type consisting of an array of bits, with each bit directly accessible for read/write operations, in a sense they already exist as native integer types, unsigned char, unsigned int, etc. Utilizing the bitwise NOT (~), OR (|), AND (&), XOR (^), left shift (<<) and right shift (>>) operators combine with an appropriate bitmask when necessary, each bit of native integer type can be bitwise manipulated, essentially independently read or set.

While Alex's tutorial is primarily focused on PORT registers, the same techniques can certainly be applied to an unsigned integer variable type:

Accessing individual PORT bits in AVR with avrgcc

Learning C (Part 4): Bitwise Operators

Bitwise Operators

Another possible option is to utilize a packed structure of bit fields, which can simplify bitwise manipulations while provide a more intuitive method.

Alex's aforementioned tutorial provides an example of utilizing a structure of bit fields, the following tutorial explains packed structure techniques which can significantly reduce data storage requirements in some cases.

The Lost Art of C Structure Packing

Bit field

Bitwise operators have been a standard feature of the C language since C89 (ANSI), however some of the details of bit field structures were not finalized until later ISO standards, therefore you should examine the Mikro C documentation concerning the specifics of its support for bit field structures.

BigDog

Last edited by a moderator:

Status
Not open for further replies.