Two's complement: Difference between revisions
Content added Content deleted
(Added Algol W) |
(Added Wren) |
||
Line 155: | Line 155: | ||
761030578771 |
761030578771 |
||
0b000000000000000001011000100110000111101010001001001010011</pre> |
0b000000000000000001011000100110000111101010001001001010011</pre> |
||
=={{header|Wren}}== |
|||
Strictly speaking, Wren doesn't have integers. Instead all numbers are 'IEEE 754' 64 bit floating point values (their underlying C type being ''double'') and negative numbers are therefore represented using the ''offset binary'' method rather than ''two's complement''. |
|||
This is illustrated by running the following code: |
|||
<lang ecmascript>var a = 0 |
|||
a = -a |
|||
System.print(a) // -0</lang> |
|||
which produces 'negative zero' rather than just 'zero'. |
|||
However, when using the bitwise operators, Wren's VM emulates the corresponding operation in C by first converting the operands to ''unsigned'' 32 bit values, performing the operation and then converting the result back to a double. |
|||
We can therefore emulate how two's complement works on ''signed'' 32 bit integers by using the bitwise complement operator '''~''' to flip the bits as follows: |
|||
<lang ecmascript>var pow32 = 2.pow(32) |
|||
var pow31 = 2.pow(31) |
|||
var bs = [-pow31, -pow31+1, -2, -1, 0, 1, 2, pow31-2, pow31-1] |
|||
for (b in bs) { |
|||
var b2 = ~b + 1 |
|||
if (b2 > pow31) b2 = b2 - pow32 |
|||
System.print("%(b) -> %(b2)") |
|||
}</lang> |
|||
{{out}} |
|||
<pre> |
|||
-2147483648 -> 2147483648 |
|||
-2147483647 -> 2147483647 |
|||
-2 -> 2 |
|||
-1 -> 1 |
|||
0 -> 0 |
|||
1 -> -1 |
|||
2 -> -2 |
|||
2147483646 -> -2147483646 |
|||
2147483647 -> -2147483647 |
|||
</pre> |
|||
=={{header|Z80 Assembly}}== |
=={{header|Z80 Assembly}}== |