Hi
i was trying to do some bit setting / shifting on a 32 bit integer - unsigned long. So i thought i would test a loop to turn all bits to 0, but it didn't return what i expected. i expected it to continue turning all the 1's to 0's rather than stopping half way and printing 0's for the rest of the loop as it does below. I think i must misunderstand the implication or be using the wrong data type or something. please help.
unsigned long i;
void setup() {
Serial.begin(9600);
}
void loop(){
i = 4294967295;
Serial.println(i, BIN);
for(int f = 0; f < 31; f++){
i &= ~(1<<f);
Serial.println(i, BIN);
}
delay(3000);
}
Because the expression ~(1<<f) is a 16-bit integer. If you change it to ~(1UL<<f) it will work.
Mikal
EDIT: Better yet, for the benefit of your code's readers, make i a uint32_t and use ~((uint32_t)1 << f). That way, it's very clear to everyone that you mean to use 32-bit numbers.
ok - i thought i would be able to reach 4294967295 using bit shifting, but my number goes into the negative. I thought if it was unsigned it would always be positive ? i appreciate the 2's complement rule but doesnt that only apply to signed ints' ?
the code
uint32_t i;
void setup() {
Serial.begin(9600);
}
void loop(){
i = 0;
for(int f = 0; f < 32; f++){
i |= (1UL << f);
Serial.println(i, BIN);
Serial.println(i, DEC);
}
for(int f = 0; f < 32; f++){
i &= ~(1UL << f);
Serial.println(i, BIN);
Serial.println(i, DEC);
}
delay(3000);
}
and never reaches 4294967295 which i thought was the upper limit of an unsigned long / 32 bit number, and i presumed would be represented with 32 1's - can some one please explaing my missunderstanding - thanks