Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you bit shift beyond the end of a variable?

If you have some variable (on the stack) and you left or right bit shift beyond its end what happens?

i.e.

byte x = 1;
x >> N;

What if x is a pointer to memory cast to a byte and you do the same thing?

byte* x = obtain pointer from somewhere;
*x = 1;
*x >> N;
like image 363
Percy Flarge Avatar asked Dec 01 '10 23:12

Percy Flarge


People also ask

What happens when you shift bits to the left?

When shifting left, the most-significant bit is lost, and a 0 bit is inserted on the other end. The left shift operator is usually written as "<<".

How does bitwise Shift Work?

The bitwise shift operators move the bit values of a binary object. The left operand specifies the value to be shifted. The right operand specifies the number of positions that the bits in the value are to be shifted. The result is not an lvalue.

What effect does a left shift of 2 places have in binary?

To multiply a number, a binary shift moves all the digits in the binary number along to the left and fills the gaps after the shift with 0: to multiply by two, all digits shift one place to the left. to multiply by four, all digits shift two places to the left.

What does left shift operator do?

The left shift operator ( << ) shifts the first operand the specified number of bits, modulo 32, to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.


2 Answers

It does not (necessarily) become zero. The behavior is undefined (C99 §6.5.7, "Bitwise shift operators"):

If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

(C++0x §5.8, "Shift operators"):

The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

The storage of the value being shifted has no effect on any of this.

like image 182
Stephen Canon Avatar answered Sep 22 '22 18:09

Stephen Canon


I think you're confused about what bitshifts do. They are arithmetic operators equivalent to multiplication or division by a power of 2 (modulo some weirdness about how C treats negative numbers). They do not move any bits in memory. The only way the contents of any variable/memory get changed are if you assign the result of the expression back somewhere.

As for what happens when the righthand operand of a bitshift operator is greater than or equal to the width of the type of the lefthand expression, the behavior is undefined.

like image 29
R.. GitHub STOP HELPING ICE Avatar answered Sep 23 '22 18:09

R.. GitHub STOP HELPING ICE