Pages: [1]   Go Down
Author Topic: bit shifting unsigned long  (Read 1018 times)
0 Members and 1 Guest are viewing this topic.
Enschede - The Netherlands
Offline Offline
Jr. Member
**
Karma: 0
Posts: 75
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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);
}

Logged

Forum Administrator
Cambridge, MA
Offline Offline
Faraday Member
*****
Karma: 12
Posts: 3538
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

Enschede - The Netherlands
Offline Offline
Jr. Member
**
Karma: 0
Posts: 75
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

Thank you, that solved the problem.
Logged

Pages: [1]   Go Up
Jump to: