Follow

the dirtiest average-of-two-integers code I've ever seen, from a great page on optimizing C:

avg = (x & y) + ((x ^ y) >> 1);

before optimizing:

a = (x + y) >>1;
/* overflow fixup */
if( a <x &&a <y ) a += 0x8000000;

(the page is azillionmonkeys.com/qed/optimi, by the way)

@danielhglus On uints it looks safe. Signed, I'm gonna (a-b)/2+b.

Coincidentally, I imagine that's what the HDL for an ALU adder looks like, except << the & instead of >> the ^.

@octet33 works for me in... uh... Python with signed ints

nice observation w/ the HDL, wish I'd used it more

@danielhglus Yeah, tried it once for an extracurricular.

Problems arose trying to get it to talk with the onboard ARM chip, and we abandoned the project for simpler designs. To this day I maintain that FPGA stands for Frustratingly Problematic Gate Array.

@danielhglus Hoping to do something actually interesting with it in my coursework. I'm a computer engineering major, so it's probable.

@octet33 nice

yeah I was reading about optimizations for a compiler side project, might even be able to use a few

@danielhglus How about

x_ = x & 1, x >>= 1;
y_ = y & 1, y >>= 1;
z = x + y, z += x_ & y_;

for overflow protection?

@amiloradovsky hey! x and y aren't monadic values! :p

...yeah, looks good to me. compiler might have a fun time move-coalescing (wild guess, probably I'm wrong) that one

@danielhglus It's funny how people nowadays think of "bind" before all when seeing this…

Sign in to participate in the conversation
Mastodon for Tech Folks

The social network of the future: No ads, no corporate surveillance, ethical design, and decentralization! Own your data with Mastodon!