Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if we bitwise shift an integer more than its size [duplicate]

Tags:

c

bit-shift

On Visual Studio compiling following C code , the result is 4 .

void main() { int c = 1; c = c<<34;}

The assembly code as seen from on Visual Studio disassembly window is

shl eax,22h

From assembly , its easy to see that we are shifting 34. Since the integer here is 4 bytes , from the results it is obvious that modulo operation was carried out on machine level to make this work as shift by 2.

I was wondering if this behavior is standardized across platforms or varies across platforms?

like image 368
Manik Mahajan Avatar asked Apr 20 '13 16:04

Manik Mahajan


People also ask

What happens when you bit shift an integer?

Logical bit shifting may be useful for multiplying or dividing unsigned integers by powers of two. For example, if the value "0001" or "1" is shifted left, it becomes "0010" or "2," shifted to the left again it becomes "0100," or "4." Shifting to the right has an opposite effect of dividing the value by two per shift.

What happens when we left shift a number?

Left Shifts 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 do bitwise shifts 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.

Is bit shifting faster than adding?

Bit-shifting is still faster, but for non-power-of-two mul/div by the time you do all your shifts and add the results it's slower again.


2 Answers

Undefined behavior happens. That's standardized by the language standard (See section 6.5.7 Bitwise shift operators of the C standard from 1999). The observable effects of UB are not standardized, however, and may vary.

As for shl eax, 22h, the shift count is going to be truncated to 5 bits by the CPU (see the documentation) and this instruction will really behave as shl eax, 2.

like image 200
Alexey Frunze Avatar answered Oct 03 '22 22:10

Alexey Frunze


According to this article on MSDN:

The result is undefined if the right operand of a shift expression is negative or if the right operand is greater than or equal to the number of bits in the (promoted) left operand. No shift operation is performed if the right operand is zero (0).

like image 25
Jonathan Wood Avatar answered Oct 03 '22 22:10

Jonathan Wood