3 ms·
You don't need bit shifting. You can just divide or multiply by powers of 2. (And most of the time the compiler will emit the corresponding bit shifting code.)
by amelius 5y ago
You don't need bit shifting. You can just divide or multiply by powers of 2. (And most of the time the compiler will emit the corresponding bit shifting code.)
- phoyd 5y agoWrong. (-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.