Microsoft’s Visual C compiler generates the following *branch-free* code to calculate the absolute value of an integer.

```
cdq
xor eax, edx
sub eax, edx
```

The `cdq`

instruction sign-extends eax into the register pair edx:eax. The cute trick here is to ~~ab~~use that behavior to get an all-ones register (edx) in the case of negative input. This can be used to compute the 1’s complement, and we can also subtract it to add one (for the 2’s complement). In the case of a positive input, edx is zero and thus the xor and sub are harmless.

This is faster than the naive version, which would likely contain an unpredictable branch.

I’m surely not clever enough to have written abs this way. It seems like something the Superoptimizer might have conjured up.

### Like this:

Like Loading...

*Related*

## 1 Response to “Branch-Free Absolute Value Calculation”