I'm dealing with numbers, each one represented by two bytes (a short value, in the programming sense).
I want to compute the average of these two numbers, and get once again two bytes back.
Can I just do the following?
result_byte_A = first_num_byte_A + second_num_byte_A / 2
result_byte_B = first_num_byte_B + second_num_byte_B / 2
Will this yield a correct result? Or is this more complex than that?
Apart from the fact that you accidentally multiply instead of adding, there are overflow and rounding problems. Your method suffers from these in more cases than necessary. Try
instead. (This suffers only from rounding problems, e.g., the average of $4$ and $7$ is returned as $5$ instead of $5.5$, which cannot be expressed as
short.Your method (with
+in place of*) goes awfully wrong, e.g. for $A=256$, $B=0$.