# bitshift left not working

Hi,

I have this code:

byte b = 190; //10111110
Serial.println(b << 8,BIN);

I would expect the result should be “1011111000000000” but no. I am actually getting “11111111111111111011111000000000”

Does anybody knows how to solve this?

The strange is that if b is 24 (00011000) the result is correct, it is “0001100000000000”

Thank you!

``````byte b = 190;  //10111110
Serial.println((uint16_t)b << 8,BIN);
``````

There’s nothing strange or unusual about sign extension.

I'm surprised you get anything at all. It seems odd that your result comes out as 32 bits. Shifting a byte value left 8 bits seems meaningless. If you have some particular outcome in mind, then specify exactly what you want.

to construct a number of 32 bits

``````byte a = 24;
byte b = 190;
byte c = 55;
byte d = 98;

uint32_t z = 0;

z |= (uint32_t)a << 0;
z |= (uint32_t)b << 8;
z |= (uint32_t)c << 16;
z |= (uint32_t)d << 24;
``````

having the variable z, how now I can come back to a, b, c and d know only z?

Well, if left shift put the number together, maybe right shift can take it apart.

gilperon:
Does anybody knows how to solve this?

The solution is: Write code for what you want to do!

``````  byte b = 190;  //10111110
b= b<<8; // shift all 8 bits of the byte out to the left
Serial.println(b,BIN); // nothing left, all zero
``````

And don’t get confused with the default type conversions.

When you do something like:

``````  Serial.println((some_expression),BIN);
``````

Then (some_expression) is of type “int” by default.
The default numeric type in C is always “int”.

So if you write that expression in your print command:

``````Serial.println(b << 8,BIN);
``````

the C compiler will do several conversions and calculations before printing an “int” (and NOT a “byte”).

The conversions are: Your byte ‘b’ will become a ‘short’, which is negative, then this negative ‘short’ variable will be put into an ‘int’ which will represent the same negative number. And with this int variable the actual shifting is done, and the resulting int will be printed.

So actually you wrote that:

``````  Serial.println((int)(short(b))<<8,BIN);
``````

As you are so astonished about the output, I think you didn’t realize what you really wrote to be executed in the Serial.print command. So I’d recommend:

• calculate the desired result into a variable that you want to print
• print the variable

Dont’t try compiler magic using other variable types than ‘int’ within the print command if you are clueless about C programming.