Go Down

Topic: bit shifting unsigned long (Read 1 time) previous topic - next topic

Hi,

I've a problem with bitshifting values. According to the reference a long can story 32 bit ( 4 bytes ). I would like to store an RGB value ( 3 bytes ) in a long, with bitshifting.

However, shifting 1 bit higher than 14 bits ( 1 << 15 ) doesn't seem to work.

I've made a test application, code below.
color_in and colour_out should output the same value (1), but this goes wrong when ana_0 is above 14 ( shifting with 14 bits ).

Code: [Select]

unsigned long ana_0;

void setup()
{ digitalWrite(13, HIGH);
 Serial.begin(9600);  
}

void loop()  
{ ana_0 = analogRead(0)>>5; // # between 0-32
     
 unsigned long color_in  = 1 << ana_0;
 unsigned long color_out = color_in >> ana_0;
 
 Serial.println(ana_0);
 Serial.println(color_in);
 Serial.println(color_out);
 
 delay(100);
}


mellis

I believe the problem is that the calculation 1 << ana_0 is done using integer math because the 1 is an integer.  The result is stored in an unsigned long, but only after it's overflowed.  Try declaring the constant 1 as an unsigned long: 1UL

Thank you, that solved the problem.

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy