Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the value of number left shift by -1 [duplicate]

Tags:

c

operators

shift

What is the result of number when it is left shifted by -1 in C programming using the left shift operator?

e.g.:

23 << -1
like image 713
Mithun Arunan Avatar asked Jul 21 '15 19:07

Mithun Arunan


People also ask

What does a left shift do to a number?

The number to the left of the operator is shifted the number of places specified by the number to the right. Each shift to the left doubles the number, therefore each left shift multiplies the original number by 2. Use the left shift for fast multiplication or to pack a group of numbers together into one larger number.

When any number is left shift by 1 the result is?

The left-shift of 1 by i is equivalent to 2 raised to power i. As mentioned in point 1, it works only if numbers are positive.

What is the output of left shift?

In general, if we shift a number by n position to left, the output will be number * (2n).

What is left shift left?

Shift Left is a practice intended to find and prevent defects early in the software delivery process. The idea is to improve quality by moving tasks to the left as early in the lifecycle as possible. Shift Left testing means testing earlier in the software development process.


2 Answers

From the C11 standard 6.5.7p3 (for former versions it is basically the same):

"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."

IOW: undefined behaviour. Prepare for nasal demons.

Briefly: Do not

Caution: While many programmers are aware of that and avoid negative shift counts, it is often ignored that also counts >= the bit-size of the value are also undefined. This makes something like ((unsigned int)1 << 32) - 1 actually undefined if unsigned int has 32 bits or less. For signed values things become more complicated due to the sign (thanks @chux for pointing me at that). This is a common pitfall. For some implementations, different results for constant expressions (compile-time evaluated) and run-time evaluation might occur.

like image 199
too honest for this site Avatar answered Oct 12 '22 20:10

too honest for this site


As Olaf said in his answer, left shifting by a negative number is undefined.

In fact, gcc will give a warning if you attempt shift in either direction by a negative number.

like image 36
dbush Avatar answered Oct 12 '22 19:10

dbush