<p>In C, are the shift operators (<code>&lt;&lt;</code>, <code>&gt;&gt;</code>) arithmetic or logical?</p>

[{'answer_id': 7632, 'author': 'Greg Hewgill', 'author_id': 893, 'author_profile': 'https://Stackoverflow.com/users/893', 'pm_score': 7, 'selected': False, 'text': '<p>When shifting left, there is no difference between arithmetic and logical shift. When shifting right, the type of shift depends on the type of the value being shifted.</p>\n\n<p>(As background for those readers unfamiliar with the difference, a "logical" right shift by 1 bit shifts all the bits to the right and fills in the leftmost bit with a 0. An "arithmetic" shift leaves the original value in the leftmost bit. The difference becomes important when dealing with negative numbers.)</p>\n\n<p>When shifting an unsigned value, the >> operator in C is a logical shift. When shifting a signed value, the >> operator is an arithmetic shift.</p>\n\n<p>For example, assuming a 32 bit machine:</p>\n\n<pre><code>signed int x1 = 5;\nassert((x1 &gt;&gt; 1) == 2);\nsigned int x2 = -5;\nassert((x2 &gt;&gt; 1) == -3);\nunsigned int x3 = (unsigned int)-5;\nassert((x3 &gt;&gt; 1) == 0x7FFFFFFD);\n</code></pre>\n'}, {'answer_id': 7636, 'author': 'Ronnie', 'author_id': 193, 'author_profile': 'https://Stackoverflow.com/users/193', 'pm_score': 8, 'selected': True, 'text': '<p>According to <a href="https://rads.stackoverflow.com/amzn/click/com/0131103628" rel="noreferrer" rel="nofollow noreferrer">K&amp;R 2nd edition</a> the results are implementation-dependent for right shifts of signed values.</p>\n\n<p><a href="http://en.wikipedia.org/wiki/Arithmetic_shift" rel="noreferrer">Wikipedia</a> says that C/C++ \'usually\' implements an arithmetic shift on signed values.</p>\n\n<p>Basically you need to either test your compiler or not rely on it. My VS2008 help for the current MS C++ compiler says that their compiler does an arithmetic shift.</p>\n'}, {'answer_id': 7637, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 2, 'selected': False, 'text': '<p>Well, I looked <a href="http://en.wikipedia.org/wiki/Logical_shift" rel="nofollow noreferrer">it up on wikipedia</a>, and they have this to say:</p>\n\n<blockquote>\n  <p>C, however, has only one right shift\n  operator, >>. Many C compilers choose\n  which right shift to perform depending\n  on what type of integer is being\n  shifted; often signed integers are\n  shifted using the arithmetic shift,\n  and unsigned integers are shifted\n  using the logical shift.</p>\n</blockquote>\n\n<p>So it sounds like it depends on your compiler.  Also in that article, note that left shift is the same for arithmetic and logical.  I would recommend doing a simple test with some signed and unsigned numbers on the border case (high bit set of course) and see what the result is on your compiler.  I would also recommend avoiding depending on it being one or the other since it seems C has no standard, at least if it is reasonable and possible to avoid such dependence.</p>\n'}, {'answer_id': 10101, 'author': 'Nick', 'author_id': 1236, 'author_profile': 'https://Stackoverflow.com/users/1236', 'pm_score': 4, 'selected': False, 'text': "<p>In terms of the type of shift you get, the important thing is the type of the value that you're shifting. A classic source of bugs is when you shift a literal to, say, mask off bits. For example, if you wanted to drop the left-most bit of an unsigned integer, then you might try this as your mask:</p>\n\n<pre><code>~0 &gt;&gt; 1\n</code></pre>\n\n<p>Unfortunately, this will get you into trouble because the mask will have all of its bits set because the value being shifted (~0) is signed, thus an arithmetic shift is performed. Instead, you'd want to force a logical shift by explicitly declaring the value as unsigned, i.e. by doing something like this:</p>\n\n<pre><code>~0U &gt;&gt; 1;\n</code></pre>\n"}, {'answer_id': 10518, 'author': 'Cristián Romo', 'author_id': 1256, 'author_profile': 'https://Stackoverflow.com/users/1256', 'pm_score': 0, 'selected': False, 'text': '<p><a href="/questions/tagged/gcc" class="post-tag" title="show questions tagged &#39;gcc&#39;" rel="tag">gcc</a> will typically use logical shifts on unsigned variables and for left-shifts on signed variables. The arithmetic right shift is the truly important one because it will sign extend the variable.</p>\n\n<p><a href="/questions/tagged/gcc" class="post-tag" title="show questions tagged &#39;gcc&#39;" rel="tag">gcc</a> will will use this when applicable, as other compilers are likely to do.</p>\n'}, {'answer_id': 2463888, 'author': 'John Scipione', 'author_id': 100444, 'author_profile': 'https://Stackoverflow.com/users/100444', 'pm_score': 4, 'selected': False, 'text': '<p>Here are functions to guarantee logical right shift and arithmetic right shift of an int in C:</p>\n\n<pre><code>int logicalRightShift(int x, int n) {\n    return (unsigned)x &gt;&gt; n;\n}\nint arithmeticRightShift(int x, int n) {\n    if (x &lt; 0 &amp;&amp; n &gt; 0)\n        return x &gt;&gt; n | ~(~0U &gt;&gt; n);\n    else\n        return x &gt;&gt; n;\n}\n</code></pre>\n'}, {'answer_id': 12293923, 'author': 'Srikant Patnaik', 'author_id': 1650989, 'author_profile': 'https://Stackoverflow.com/users/1650989', 'pm_score': 3, 'selected': False, 'text': '<p>When you do \n - left shift by 1 you multiply by 2\n - right shift by 1 you divide by 2</p>\n\n<pre><code> x = 5\n x &gt;&gt; 1\n x = 2 ( x=5/2)\n\n x = 5\n x &lt;&lt; 1\n x = 10 (x=5*2)\n</code></pre>\n'}, {'answer_id': 19978070, 'author': 'srinath', 'author_id': 2952286, 'author_profile': 'https://Stackoverflow.com/users/2952286', 'pm_score': -1, 'selected': False, 'text': '<p>According to many <a href="/questions/tagged/c" class="post-tag" title="show questions tagged &#39;c&#39;" rel="tag">c</a> compilers:</p>\n\n<ol>\n<li><code>&lt;&lt;</code> is an arithmetic left shift or bitwise left shift.</li>\n<li><code>&gt;&gt;</code> is an arithmetic right shiftor bitwise right shift.</li>\n</ol>\n'}, {'answer_id': 22734721, 'author': 'legends2k', 'author_id': 183120, 'author_profile': 'https://Stackoverflow.com/users/183120', 'pm_score': 6, 'selected': False, 'text': '<h1>TL;DR</h1>\n<p>Consider <code>i</code> and <code>n</code> to be the left and right operands respectively of a shift operator; the type of <code>i</code>, after integer promotion, be <code>T</code>.  Assuming <code>n</code> to be in <code>[0, sizeof(i) * CHAR_BIT)</code> — undefined otherwise — we\'ve these cases:</p>\n<pre><code>| Direction  |   Type   | Value (i) | Result                   |\n| ---------- | -------- | --------- | ------------------------ |\n| Right (&gt;&gt;) | unsigned |    ≥ 0    | −∞ ← (i ÷ 2ⁿ)            |\n| Right      | signed   |    ≥ 0    | −∞ ← (i ÷ 2ⁿ)            |\n| Right      | signed   |    &lt; 0    | Implementation-defined†  |\n| Left  (&lt;&lt;) | unsigned |    ≥ 0    | (i * 2ⁿ) % (T_MAX + 1)   |\n| Left       | signed   |    ≥ 0    | (i * 2ⁿ) ‡               |\n| Left       | signed   |    &lt; 0    | Undefined                |\n</code></pre>\n<p><sup>† most compilers implement this as arithmetic shift</sup><br />\n<sup>‡ undefined if value overflows the result type T; promoted type of i</sup></p>\n<hr />\n<h1>Shifting</h1>\n<p>First is the difference between logical and arithmetic shifts from a mathematical viewpoint, without worrying about data type size. Logical shifts always fills discarded bits with zeros while arithmetic shift fills it with zeros only for left shift, but for right shift it copies the MSB thereby preserving the sign of the operand (assuming a <a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="noreferrer">two\'s complement</a> encoding for negative values).</p>\n<p>In other words, logical shift looks at the shifted operand as just a stream of bits and move them, without bothering about the sign of the resulting value. Arithmetic shift looks at it as a (signed) number and preserves the sign as shifts are made.</p>\n<p>A left arithmetic shift of a number X by n is equivalent to multiplying X by 2<sup>n</sup> and is thus equivalent to logical left shift; a logical shift would also give the same result since MSB anyway falls off the end and there\'s nothing to preserve.</p>\n<p>A right arithmetic shift of a number X by n is equivalent to integer division of X by 2<sup>n</sup> ONLY if X is non-negative! Integer division is nothing but mathematical division and <a href="http://en.wikipedia.org/wiki/Rounding#Rounding_to_integer" rel="noreferrer">round</a> towards 0 (<a href="http://en.cppreference.com/w/c/numeric/math/trunc" rel="noreferrer">trunc</a>).</p>\n<p>For negative numbers, represented by two\'s complement encoding, shifting right by n bits has the effect of mathematically dividing it by 2<sup>n</sup> and rounding towards −∞ (<a href="http://en.cppreference.com/w/c/numeric/math/floor" rel="noreferrer">floor</a>); thus right shifting is different for non-negative and negative values.</p>\n<blockquote>\n<p>for X ≥ 0, X &gt;&gt; n = X / 2<sup>n</sup> = trunc(X ÷ 2<sup>n</sup>)</p>\n<p>for X &lt; 0, X &gt;&gt; n = floor(X ÷ 2<sup>n</sup>)</p>\n</blockquote>\n<p>where <code>÷</code> is mathematical division, <code>/</code> is integer division. Let\'s look at an example:</p>\n<blockquote>\n<p>37)<sub>10</sub> = 100101)<sub>2</sub></p>\n<p>37 ÷ 2 = 18.5</p>\n<p>37 / 2 = 18 (rounding 18.5 towards 0) = 10010)<sub>2</sub> [result of arithmetic right shift]</p>\n<p>-37)<sub>10</sub> = 11011011)<sub>2</sub> (considering a two\'s complement, 8-bit representation)</p>\n<p>-37 ÷ 2 = -18.5</p>\n<p>-37 / 2 = -18 (rounding 18.5 towards 0) = 11101110)<sub>2</sub> [NOT the result of arithmetic right shift]</p>\n<p>-37 &gt;&gt; 1 = -19 (rounding 18.5 towards −∞) = 11101101)<sub>2</sub> [result of arithmetic right shift]</p>\n</blockquote>\n<p>As <a href="http://dspace.mit.edu/bitstream/handle/1721.1/6090/AIM-378.pdf" rel="noreferrer">Guy Steele pointed out</a>, this discrepancy has led to <a href="http://en.wikipedia.org/wiki/Arithmetic_shift" rel="noreferrer">bugs in more than one compiler</a>. Here non-negative (math) can be mapped to unsigned and signed non-negative values (C); both are treated the same and right-shifting them is done by integer division.</p>\n<p>So logical and arithmetic are equivalent in left-shifting and for non-negative values in right shifting; it\'s in right shifting of negative values that they differ.</p>\n<h2>Operand and Result Types</h2>\n<p><em>Standard C99 §6.5.7</em>:</p>\n<blockquote>\n<p>Each of the operands shall have integer types.</p>\n<p>The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behaviour is undefined.</p>\n</blockquote>\n<pre><code>short E1 = 1, E2 = 3;\nint R = E1 &lt;&lt; E2;\n</code></pre>\n<p>In the above snippet, both operands become <code>int</code> (due to integer promotion); if <code>E2</code> was negative or <code>E2 ≥ sizeof(int) * CHAR_BIT</code> then the operation is undefined. This is because shifting more than the available bits is surely going to overflow. Had <code>R</code> been declared as <code>short</code>, the <code>int</code> result of the shift operation would be implicitly converted to <code>short</code>; a narrowing conversion, which may lead to implementation-defined behaviour if the value is not representable in the destination type.</p>\n<h1>Left Shift</h1>\n<blockquote>\n<p>The result of E1 &lt;&lt; E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1×2<sup>E2</sup>, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and non-negative value, and E1×2<sup>E2</sup> is representable in the result type, then that is the resulting value; otherwise, the behaviour is undefined.</p>\n</blockquote>\n<p>As left shifts are the same for both, the vacated bits are simply filled with zeros. It then states that for both unsigned and signed types it\'s an arithmetic shift. I\'m interpreting it as arithmetic shift since logical shifts don\'t bother about the value represented by the bits, it just looks at it as a stream of bits; but the standard talks not in terms of bits, but by defining it in terms of the value obtained by the product of E1 with 2<sup>E2</sup>.</p>\n<p><strong>The caveat here is that for signed types the value should be non-negative and the resulting value should be representable in the result type. Otherwise the operation is undefined.</strong> The result type would be the type of the E1 after applying integral promotion and not the destination (the variable which is going to hold the result) type. The resulting value is implicitly converted to the destination type; if it is not representable in that type, then the conversion is implementation-defined (C99 §6.3.1.3/3).</p>\n<p><strong>If E1 is a signed type with a negative value then the behaviour of left shifting is undefined.</strong> This is an easy route to undefined behaviour which may easily get overlooked.</p>\n<h1>Right Shift</h1>\n<blockquote>\n<p>The result of E1 &gt;&gt; E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a non-negative value, the value of the result is the integral part of the quotient of E1/2<sup>E2</sup>. If E1 has a signed type and a negative value, the resulting value is implementation-defined.</p>\n</blockquote>\n<p>Right shift for unsigned and signed non-negative values are pretty straight forward; the vacant bits are filled with zeros. <strong>For signed negative values the result of right shifting is implementation-defined.</strong> That said, most implementations like GCC and <a href="http://en.wikipedia.org/wiki/Visual_C%2B%2B#32-bit_versions" rel="noreferrer">Visual C++</a> implement right-shifting as arithmetic shifting by preserving the sign bit.</p>\n<h1>Conclusion</h1>\n<p>Unlike Java, which has a special operator <code>&gt;&gt;&gt;</code> for logical shifting apart from the usual <code>&gt;&gt;</code> and <code>&lt;&lt;</code>, C and C++ have only arithmetic shifting with some areas left undefined and implementation-defined. The reason I deem them as arithmetic is due to the standard wording the operation mathematically rather than treating the shifted operand as a stream of bits; this is perhaps the reason why it leaves those areas un/implementation-defined instead of just defining all cases as logical shifts.</p>\n'}, {'answer_id': 22743208, 'author': 'asifaftab87', 'author_id': 2673577, 'author_profile': 'https://Stackoverflow.com/users/2673577', 'pm_score': 0, 'selected': False, 'text': '<p>Left shift <code>&lt;&lt;</code> </p>\n\n<p>This is somehow easy and whenever you use the shift operator, it is always a bit-wise operation, so we can\'t use it with a double and float operation. Whenever we left shift one zero, it is always added to the least significant bit (<code>LSB</code>).</p>\n\n<p>But in right shift <code>&gt;&gt;</code> we have to follow one additional rule and that rule is called "sign bit copy". Meaning of "sign bit copy" is if the most significant bit (<code>MSB</code>) is set then after a right shift again the <code>MSB</code> will be set if it was reset then it is again reset, means if the previous value was zero then after shifting again, the bit is zero if the previous bit was one then after the shift it is again one. This rule is not applicable for a left shift. </p>\n\n<p>The most important example on right shift if you shift any negative number to right shift, then after some shifting the value finally reach to zero and then after this if shift this -1 any number of times the value will remain same. Please check.</p>\n'}, {'answer_id': 48708328, 'author': 'Alok Prasad', 'author_id': 4869319, 'author_profile': 'https://Stackoverflow.com/users/4869319', 'pm_score': -1, 'selected': False, 'text': '<p>GCC does </p>\n\n<ol>\n<li><p>for -ve - > Arithmetic Shift</p></li>\n<li><p>For +ve  -> Logical Shift </p></li>\n</ol>\n'}]
['https://Stackoverflow.com/questions/7622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/973/']