4 ms·
Isn't it better to do (a>>1) + (b>>1) + (a&b&1) No division needed.
by bufferoverflow 5y ago
Isn't it better to do
(a>>1) + (b>>1) + (a&b&1)
No division needed.
- jws 5y agoYour compiler will take care of that. Leave the division for the humans to read.
- xaduha 5y agoI'm in a camp that thinks compilers should also take care of the original unsigned average(unsigned a, unsigned b) { return (a + b) / 2; } At the end of the day it's all just text. There are plenty of steps before any of it does anything at all.
- Dylan16807 5y agoWhat should happen if you store "a+b" in an intermediate value?
- xaduha 5y agoIf it is used and there's no way around it, then show a compilation warning that there might be overflow. If it can be resolved without being directly used, then it should be optimized away.
- jws 5y agoFor C at least, the spec says that unsigned addition is modulo 2^64 (or 32 or 16 or whatever) so, imagine you had an 8 bit unsigned, 128+128 gives you 0. Divided by 2 is 0. That’s the right answer by the language specification. The trick is to get 128.
- 8jy89hui 5y agoNot really. It is harder for most programmers to read (a>>1) than the simpler (a/2) and in most modern programming languages the compiler will notice the division by a power of two and compile to bit shift operations in both cases.
- marginalia_nu 5y ago> most programmers Really depends on where you're coming from. Anyone who has dipped their toes in embedded programming will immediately know they are equivalent, and many will correct /2 to a bitshift, because that's what you want to happen. I get that bit twiddling is obscure outside of low level programming, but bit shifts really is kindergarten stuff in this domain.