Loading...
Pages: [1]   Go Down
Author Topic: Bit wise problem  (Read 265 times)
0 Members and 1 Guest are viewing this topic.
Yorkshire England
Offline Offline
Sr. Member
****
Karma: 1
Posts: 253
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: 222
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: 16
Posts: 1214
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

I'm not kidding. If I am asking a question whose answer is found within the concerned product's datasheet, shame on me. If I am answering a similar question, shame on you!

0
Offline Offline
Full Member
***
Karma: 0
Posts: 230
Arduino rocks
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
Print
 
Jump to: