Arduino UNO -Bitwise

Hello

Please explain why shifting the binary value of 00000011 (Dec 3) one time to the left -
giving me 00001000 ? >:(

By many tutorials this should gives: 00001100

Thank you ahead
Eyal

bitwise.ino (377 Bytes)

This is your code:

unsigned int i;

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  for (i=0; i<5;i++)
  {		
    Serial.print("I=");
    Serial.print(i,BIN);
    Serial.print(" After Shifting=");
    unsigned int j = 1<<i;		
    Serial.println(j,BIN);
    delay(1000);
  }				
  while (Serial.available() == 0) {	
  }
}

You are not shifting 3 left one, you are shifting 1 left 0, 1, 2, 3, 4.

How do you declare that binary - did you put B00000011 or 0b00000011? Is it a register?

Edit - ignore I had not seen the code. Yes Nick is right, as always.

It's my first time posting here..anyway many thanks letting me know.

The attached code just show what happened during shifting from 0 to 4.

But see the below code:

int i = B00000011;
int j = 1<<i;

The result by the Arduino is: B00001000

But from my understanding the result should be: B00000110

Can you please explain why?

Many thanks

No problem for being a first - come back and share with the community!

you understood your pb right?

you did

    unsigned int j = 1<<i;

instead of

    unsigned int j = i<<i;

(notice the i instead of 1)

if you shift a 1 (B00000001) by 3 positions left you get B00001000 - feels normal
if you shift a 3 (B00000011) by 3 positions left you will get B00011000

Just to be sure I understood you well:
The correct syntax is: j = i<<1

and not: j = 1<<i

Thank you very much!

Yes - you got it

if you do

j = i<<1;

then you shift the value of i by 1 bit to the left.

or in more general terms:

if you do a << 3 it means take the binary representation of the variable a and shift the bits in there to the left 3 times

so when you do 1 << i you are shift the bits representing 1 3 times to the left

if you do i << 1 then you are shifting the bits representing i 1 time to the left

if you do i << i then you are shifting the bits representing i i times to the left

Thank you very much and have a nice day!

pleasure if that was helpful.