3 ms·
Wrong. (-1/2) is 0, (-1>>1) is -1 in C/C++/Java/C#...
by phoyd 5y ago
Wrong. (-1/2) is 0, (-1>>1) is -1 in C/C++/Java/C#...
- amelius 5y agoYeah, the signed case needs some care (and in fact has special shift operators in instruction sets).
- kazinator 5y agoWrong. -1 >> 1 produces an implementation-defined value in C. -1/2 used to also be implementation-defined; C99 started to require truncation toward zero. That actually makes division unsuitable for simulating bit shifting; you generally want a right shift of a negative quantity to have predictable behavior: either extend the sign, or bring in a zero. Truncating division toward zero doesn't do either; it propagates the sign, until zero is hit. If you can, avoid signed types if you're working with bit fields.