Skip to content

Instantly share code, notes, and snippets.

@adamvduke
adamvduke / BitwiseMagic.c
Created August 29, 2012 00:17
A C function to compute an average without the risk of integer overflow
#include <stdio.h>
/* https://twitter.com/mikeash/status/240471662422810624
* Compute average with no possibility of integer overflow.
* Note: patented in 1996, so you can't use it!
*/
int patentedAverage(int a, int b)
{
int av = (a/2) + (b/2) + (a&b&1);
return av;