bit-shift

Why doesn&#39;t left bit-shift, “<<”, for 32-bit integers work as expected when used more than 32 times?

 ̄綄美尐妖づ 提交于 2019-11-26 00:24:25
问题 When I write the following program and use the GNU C++ compiler, the output is 1 which I think is due to the rotation operation performed by the compiler. #include <iostream> int main() { int a = 1; std::cout << (a << 32) << std::endl; return 0; } But logically, as it\'s said that the bits are lost if they overflow the bit width, the output should be 0. What is happening? The code is on ideone, http://ideone.com/VPTwj. 回答1: This is caused due to a combination of an undefined behaviour in C

Are the shift operators (<<, >>) arithmetic or logical in C?

∥☆過路亽.° 提交于 2019-11-25 23:25:01
问题 In C, are the shift operators ( << , >> ) arithmetic or logical? 回答1: According to K&R 2nd edition the results are implementation-dependent for right shifts of signed values. Wikipedia says that C/C++ 'usually' implements an arithmetic shift on signed values. 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. 回答2: When shifting left, there is no difference between arithmetic and

What is the JavaScript >>> operator and how do you use it?

梦想与她 提交于 2019-11-25 22:28:58
问题 I was looking at code from Mozilla that add a filter method to Array and it had a line of code that confused me. var len = this.length >>> 0; I have never seen >>> used in JavaScript before. What is it and what does it do? 回答1: It doesn't just convert non-Numbers to Number, it converts them to Numbers that can be expressed as 32-bit unsigned ints. Although JavaScript's Numbers are double-precision floats(*), the bitwise operators ( << , >> , & , | and ~ ) are defined in terms of operations on

Right shifting negative numbers in C

别等时光非礼了梦想. 提交于 2019-11-25 19:40:43
I have C code in which I do the following. int nPosVal = +0xFFFF; // + Added for ease of understanding int nNegVal = -0xFFFF; // - Added for valid reason Now when I try printf ("%d %d", nPosVal >> 1, nNegVal >> 1); I get 32767 -32768 Is this expected? I am able to think something like 65535 >> 1 = (int) 32767.5 = 32767 -65535 >> 1 = (int) -32767.5 = -32768 That is, -32767.5 is rounded off to -32768. Is this understanding correct? It looks like your implementation is probably doing an arithmetic bit shift with two's complement numbers. In this system, it shifts all of the bits to the right and