Principle#
To find the absolute value of a number, you simply convert a negative number to a positive one, which can be achieved by calculating its two's complement (one's complement plus one).
Code#
Principle Analysis#
Taking -12 as an example: the two's complement of -12 is 10100
(assuming the machine word length is 5 bits).
The steps are as follows:
-
First, obtain the mask
mask
:Shifting
10100
left by 4 bits gives11111
. Note that11111
is a very clever design.The reason we choose to right shift to obtain the mask instead of directly right shifting four bits and using & with 0x1 to get the sign bit is that: the mask
11111
is actually entirely composed of the sign bit. If the sign bit is 1, the generated mask can be directly XORed with the original data to get the one's complement, and then adding 1 gives the two's complement.If the sign bit is 0, the resulting mask will be all 0s, and XORing 0 with any number yields the number itself.
-
Calculate the one's complement:
As shown in the previous step,
10100
XOR11111
equals01011
, which gives the one's complement.If a positive number were here, the mask would be
00000
, and XORing would leave it unchanged. -
Add 1:
01011
-11111
=01100
, resulting in the absolute value of -12, which is 12.The reason adding one becomes subtracting the mask is simple: the mask we obtained earlier is
11111
, which is actually the two's complement of -1. To add 1, we just need to subtract the mask.If a positive number were here, the mask would be
00000
, and subtracting 0 would have no effect.
In this way, we have implemented the algorithm for calculating the absolute value. A negative number will be converted to a positive one, while a positive number remains unchanged. Isn't it simple?
Benchmark#
Below are the results obtained using a MacBook Air (M1, 2020) and Apple clang 13.1.6
Below are the results obtained using i5-9500 and gcc 8.5.0 (Red Hat 8.5.0-10)