Hacker News new | ask | show | jobs
by phoyd 1783 days ago
Wrong. (-1/2) is 0, (-1>>1) is -1 in C/C++/Java/C#...
2 comments

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

Yeah, the signed case needs some care (and in fact has special shift operators in instruction sets).