Convert bit pattern array to int

Hey there!

Ive got an int array like this:

Int someArray[8] = [0,0,1,0,0,0,1,0]

And i would like to convert the whole bit pattern into an int (here: 34).

B00100010 = 34

Is there any technique to do so?

Thanks in advance!

Iterate through the array and bitWrite() the corresponding bit in an int variable ?

Int someArray[8] = [0,0,1,0,0,0,1,0]

byte someArray[] = {0b00100010, 0x22, }; // 2 ways to show same #, not an int just a byte

loop could look like this

int value = 0;
for (byte i=0; i<8; i++)
{
  value *= 2;
  value += somearray[i] ;
}
Serial.println(value, HEX);  // or DEC

Thanks guys for your solutions so far!

An example of bitWrite() would be interessting too! :slight_smile:

Maybe some bit shifting would do also?
Something like (its not working, just an idea):

byte aVal;

for(int i=0;i<8;i++)
{
     aVal = someArray[i] << 1
}

Something like this

uint8_t aVal;

for ( uint8_t i = 0; i < 8; i++ )
{
    aVal = aVal << 1 | someArray[i];
}

I have little doubt that the compiler turns times and divided by powers of 2 into bit shifts.

A bit of learning can go far.

An example of bitWrite() would be interessting too!

byte someArray[8] = {0, 0, 1, 0, 0, 0, 1, 0};
int someInt = 0;

void setup()
{
  Serial.begin(115200);
  for (int bit = 0; bit < 8; bit++)
  {
    bitWrite(someInt, 7 - bit, someArray[bit]);
  }
  Serial.println(someInt);
}

void loop()
{
}

Questions :
As the array only contains 0 or 1 why is it an array of ints rather than bytes ?
As you only have 8 entries in the array why is the target an int rather than a byte ?

That's why I put the link there, Bob.

Somebody is looking for ways around... what they don't know, the usual pattern.

This is another problem made easy using my BitBool library.

You can control each bit in the set using array like syntax. It can be viewed as an array of bits.

[color=maroon]bits[ 0 ] = 1;     //Write a bit.
bits[ 1 ] = true;

if( bits[ 15 ] ){  //Read a bit.

}[/color]

Here is an example of how to achieve what you want.

#include <BitBool.h>

BitBool<8,true> bits = { B00100010 };  //Eight bits. Bit access reversed (bit 0 becomes bit 7...).

void setup() {

  Serial.begin( 9600 );
  
  Serial.print( "value of the first 8 bits in the BitBool: " );
  Serial.println( bits.data[0], DEC );
  
  Serial.print( "Each bit's value: {" );
  
  for( int i = 0 ; i < bits.bitCount ; ++i ){
  
    Serial.print( bits[ i ] ? 1 : 0 );
    Serial.print( ',' );
  }
  Serial.print( "}" );
}

void loop(){}

This code outputs:

value of the first 8 bits in the BitBool: 34
Each bit’s value: {0,0,1,0,0,0,1,0,}