Problem getting the bits of a bool [32] into an unsigned long int.

Hi guys,

I’m having trouble in transforming the 1’s and 0’s of a boolean vector into a variable.
My code is as follows:

bool bits[32];
unsigned long int ulbits = 0;

//some commands that give some value to the vector

for (int i = 0; i < 32; i++) {
      ulbits |= bits[i] << i;
      Serial.print(bits[31-i]);
    }
Serial.println("");
Serial.println(ulbits, BIN);
Serial.println("");

In the Monitor:

00101010101010101010101010100000
11111111111111111010101010100000

I noticed that the 16 LSB of ulbits went out correctly, but all the rest was 1. What’s wrong and how can I make that variable have the same binary value as the vector?

Thank you very much!

bits[i] << i

Is evaluated as an “int” which is 16 bits wide on an eight bit Arduino.
Obviously, you can’t represent a 32 bit number in 16 bits.

Use a cast to promote “bits[ i ]” to unsigned long.

Thank you, AWOL, I'll try to do that next time and let you know if it went well! :smiley:

Thanks for your help, it worked!
But what I don’t get is why it works in CodeBlocks like this:

#include <stdio.h>
#include <stdbool.h>

int main()
{
    unsigned long int ulbits = 0;
    bool bits[32] = {1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0};
    int i = 0;
    while(i < 32){
        ulbits |= bits[i] << i;
        printf("%d", bits[31-i]);
        i++;
    }
    printf("\n%lu",ulbits);
    return 0;
}

while in Arduino it only works when I use unsigned long int instead of bool in the code below:

void setup() {
  Serial.begin(9600);
}
void loop() {
  unsigned long int ulbits = 0;
  bool bits[32] = {1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0};
  int i = 0;
  while (i < 32) {
    ulbits |= bits[i] << i;
    Serial.print(bits[31 - i]);
    i++;
  }
  Serial.println("");
  Serial.println(ulbits, BIN);
  while(1){}
}

Anyway, thanks a lot! :smiley:

Because not all "int"s are equal (or at least, not all the same size)