News for hackers. Stuff that matters.
Re:A Bit Overcomplicated by amelius on Thursday August 05, 2021 @09:57AM (#28073793)
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.)
Re:A Bit Overcomplicated by phoyd on Thursday August 05, 2021 @10:20AM (#28074088)
Wrong. (-1/2) is 0, (-1>>1) is -1 in C/C++/Java/C#...
Re:A Bit Overcomplicated by kazinator on Thursday August 05, 2021 @11:22AM (#28074994)
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.

Re:A Bit Overcomplicated by amelius on Thursday August 05, 2021 @11:05AM (#28074740)
Yeah, the signed case needs some care (and in fact has special shift operators in instruction sets).