Two's complement: Difference between revisions

Created Nim solution.
(Created Nim solution.)
Line 154:
=={{header|Julia}}==
In Julia as in C, if a number n is any integer type, then -n is the two's complement of n, with type preserved. This is true even if n is unsigned.
 
=={{header|Nim}}==
We define a function to compute the two’s complement by taking the logical complement and adding one. As Nim uses the native complement of the computer, which is two’s complement, the result should be equal to the arithmetic negation.
 
<syntaxhighlight lang="Nim">import std/[strformat, strutils]
 
func twosComplement[T: SomeSignedInt](n: T): T =
## Compute the two's complement of "n".
not n + 1
 
echo &"""{"n":^15}{"2's complement":^15}{"-n":^15}"""
for n in [0i32, 1i32, -1i32]:
echo &"{n.toHex:^15}{twosComplement(n).toHex:^15}{(-n).toHex:^15}"
for n in [-50i8, 50i8]:
echo &"{n.toHex:^15}{twosComplement(n).toHex:^15}{(-n).toHex:^15}"
</syntaxhighlight>
 
{{out}}
<pre> n 2's complement -n
──────── ────────────── ────────
00000000 00000000 00000000
00000001 FFFFFFFF FFFFFFFF
FFFFFFFF 00000001 00000001
CE 32 32
32 CE CE
</pre>
 
=={{header|Perl}}==
256

edits