Go Down

Topic: Bit wise problem (Read 818 times) previous topic - next topic


Hi was wondering if anybody can help me with this.
Code: [Select]
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?

Professor Chaos

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


I can't find anything here. Here's an idea:
Code: [Select]

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!


Mar 16, 2011, 03:18 pm Last Edit: Mar 16, 2011, 03:43 pm by RoyK Reason: 1
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: [Select]

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.

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!

via Egeo 16
Torino, 10131