[C/C++] 無符號整數的平均值~預防 記憶體溢出(記憶體溢位/buffer overflow)
[C/C++] 無符號整數的平均值~預防 記憶體溢出(記憶體溢位/buffer overflow)
資料來源: https://mp.weixin.qq.com/s/jVLv9KeHTCsyzC-negVZpw
code01.
unsigned average(unsigned a, unsigned b) { return (a + b) / 2; }
code02.
unsigned average(unsigned low, unsigned high) { return low + (high - low) / 2; }
code03.
unsigned average(unsigned a, unsigned b) { return (a & b) + (a ^ b) / 2;// 变体 (a ^ b) + (a & b) * 2 }