Single bit array
Topic last updated
10 Feb 2010, by
Christian Lerche.
3 replies
array,
bit
Hey mbedders.
I'm trying to make a single bit array. what I'm looking for is a "char array[16];", but instead of char, I need bit.
Is it possible in C? I have already googled it, can't find it, unless i create a char, and AND's it with 0x01.
Any ideas?
/Lerche
Replies
#
10 Feb 2010 . Edited: 10 Feb 2010
if you #include <vector>, you can use std::vector<bool> which uses bits to represent elements. But why do you need it? mbed should have enough memory for a char array of a reasonable size, or even int array, and both will likely be faster than the bit array.
because in my PCA9532 program, I wan't an int (16 bit), to represent each LED (1 as on, 0 as off).
For the expander to do this, it needs at least four char's to be sent to it. A char may look like this for turning every second LED:
0b01-00-01-00 <- This is where my single bit array comes to life:
0b01-01-01-01-01-01-01-01 <- Converts to -> 0b00-01-00-01, 0b00-01-00-01, 0b00-01-00-01, 0b00-01-00-01
So I load the int into and array using for loop, but, I only wan't to use the LSB of a char, or a single bit.
This is where I need the single bit.
/ Lerche
There's no (AFAIK) easy way of converting a bool vector to an integer, so you could make a simple wrapper for setting bits in an integer:
void PCA9532_set_leds(uint16_t bits)
{
// send 'bits' value to PCA9532
}
//16-bit bit array
class Bits16
{
uint16_t m_bits;
public:
Bits16() : m_bits(0) {};
// set a bit 'bitno' to 1
void set_bit(int bitno) { m_bits |= (1<<bitno); };
// set a bit 'bitno' to 0
void clear_bit(int bitno) { m_bits &= ~(1<<bitno); };
// return the combined integer value
operator uint16_t() { return m_bits; };
};
Bits16 leds;
int main( void )
{
for ( int i=0; i < 16; i++ )
{
leds.set_bit(i);
PCA9532_set_leds(leds); // 'leds' is automatically converted to uint16_t
}
}
Please log in to post a reply.
Hey mbedders.
I'm trying to make a single bit array. what I'm looking for is a "char array[16];", but instead of char, I need bit.
Is it possible in C? I have already googled it, can't find it, unless i create a char, and AND's it with 0x01.
Any ideas?
/Lerche