On finding the average of two unsigned integers without overflow--Raymond Chen

How did you solve it?

On finding the average of two unsigned integers without overflow

by Raymond Chen

From the article:

Finding the average of two unsigned integers, rounding toward zero, sounds easy:

unsigned average(unsigned a, unsigned b)
{
    return (a + b) / 2;
}

However, this gives the wrong answer in the face of integer overflow: For example, if unsigned integers are 32 bits wide, then it says that average(0x80000000U, 0x80000000U) is zero...

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.