Pages: [1]   Go Down
Author Topic: Bit wise problem  (Read 537 times)
0 Members and 1 Guest are viewing this topic.
Yorkshire England
Offline Offline
Sr. Member
****
Karma: 2
Posts: 267
Arduino good init
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hi was wondering if anybody can help me with this.
Code:
i know i can do this

int b = a << 3;

i want to do this

int i=3;
int b = a << i;

it wont let me though

Is their a variable type for 'i' instead of an int that will work?
Logged

0
Offline Offline
Full Member
***
Karma: 1
Posts: 225
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

What do you mean "it won't let me?"  Your second fragment compiles for me if a is declared.
Logged

Connecticut
Offline Offline
Edison Member
*
Karma: 17
Posts: 1216
RTFD (Datasheet in our case)
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I can't find anything here. Here's an idea:
Code:
--pseudo-code--

for(int i = 0; i < x; i++) {
int b = a << 1;
}

and "x" could be the number of bits to shift the variable "a". It seems as if the bitshift function only allows for constants.


Good Luck!

Logged

0
Offline Offline
Sr. Member
****
Karma: 4
Posts: 329
KC4MM
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I think your problem is you are declaring the variable type on a line with a calculation. You can only initialize variables to constant values. It will work if you do it like this:

Code:
int a = 4;
int i = 3;
int b;

b = a << i;

when you do this:

int b = 4;
The compiler is able to initialize b to 4 because it knows the 'value of' 4 (it's a constant)
but when you do this:
int b = a << i;
the compiler has no idea what values a and i have so it can't initialize b and gives an error.

« Last Edit: March 16, 2011, 09:43:41 am by RoyK » Logged

Pages: [1]   Go Up
Jump to: