A clever way of determining Absolute value

hippy

Technical Support
Staff member
The usual approach for determining the absolute value of a two's complement number stored in a word variable is as follows, where the two's complement number is placed in 'w0' with the absolute value result placed in 'w1' -
Code:
w0 = -2
If w0 < $8000 Then ; Positive value in w0
  w1 = w0
Else               ; Negative value in w0
  w1 = -w0
End If
But there's another way which doesn't require an IF statement -
Code:
w1 = w0 / $8000 * $FFFF
w1 = w0 + w1 ^ w1
The first line puts -1 ($FFFF) in 'w1' when 'w0' is negative (>=$8000), and 0 in 'w1' when 'w0' is positive (< $8000).

The second line has the functionality of the following, using the trick that a number can be negated by 'inverting it and adding one' -
Code:
If Positive(w0) Then
  w1 = w0 ^ $0000 + 0 ; w1 = w0
Else
  w1 = w0 ^ $FFFF + 1 ; w1 = -w0
End If
The actual code is slightly different to that, because, for negation, 'subtracting one and inverting' is the same as 'inverting and adding one'. The actual implementation is, because "n + $FFFF" is actually "n + -1", or more simply "n - 1" -
Code:
If Positive(w0) Then
  w1 = w0 + 0 ^ $0000
Else
  w1 = w0 - 1 ^ $FFFF
End If
I can't take credit for the trick, only the PICAXE implementation. It wasn't something I was aware of. I just happened to spot it while looking for something else, thought "that's neat", and thought I'd share having spent some time figuring out how it actually worked.

Similar can be done if using byte variables to store two's complement numbers, two's complement in 'b0', absolute value result in 'b1' -
Code:
b1 = b0 / $80 * $FF
b1 = b0 + b1 ^ b1
 
Top