BASIC stamp manual v2.2
4: BASIC Stamp Architecture – Math and Operators, ABS
BASIC Stamp Syntax and Reference Manual 2.2 • www.parallax.com • Page 105
value VAR Byte
value = - 99
DEBUG SDEC ? value ' Show signed decimal result (157)
We expected -99 to be displayed but what we got was 157. How did -99
become 157? Let’s look at the bits: 99 is %01100011 binary. When the
BASIC Stamp negates 99, it converts the number to 16 bits
%0000000001100011, and then takes the two’s complement,
%1111111110011101. Since we’ve asked for the result to be placed in an 8-
bit (byte) variable, the upper eight bits are truncated and the lower eight
bits stored in the byte: %10011101.
Now for the second half of the story. DEBUG’s SDEC modifier (for all BS2
models) expects a 16-bit, two’s complement value, but we've only given it
a byte to work with. As usual, it creates a 16-bit value by padding the
leading eight bits with 0s: %0000000010011101. And what’s that in signed
decimal? 157.
To fix this problem, always store values that are intended to be signed into
a word-sized variable.
Table 4.1 lists the available Unary Operators. Note: the BS1 only supports
negative (-).
Table 4.1: Unary Operators.
Note: the BS1 only supports the
negative (-) unary operator.
Operator Description Supported By:
ABS Returns absolute value All except BS1
COS
Returns cosine in twos complement
binary radians
All except BS1
DCD 2
n
-power decoder All except BS1
~ Inverse All except BS1
- Negative All
NCD Priority encoder of a 16-bit value All except BS1
SIN
Returns sine in twos complement
binary radians
All except BS1
SQR Returns square root of value All except BS1
The Absolute Value operator (ABS) converts a signed (two’s complement)
16-bit number to its absolute value. The absolute value of a number is a
positive number representing the difference between that number and 0.
For example, the absolute value of -99 is 99. The absolute value of 99 is
also 99. ABS works on two’s complement negative numbers. Examples of
ABS at work:
ABSOLUTE VALUE: ABS
U
NARY OPERATORS.
All
2
1
A
ll
2
All
2