Two's complement: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(26 intermediate revisions by 11 users not shown)
Line 85:
<syntaxhighlight lang="c">int a = 3;
a = -a;</syntaxhighlight>
 
=={{header|C++}}==
In C++ the two's complement of an integer 'n' is its arithmetic negation '-n'.
 
The two's complement of an integer 'n' can also be calculated by adding 1 to its bitwise complement '~n'.
<syntaxhighlight lang="c++">
#include <cstdint>
#include <iostream>
#include <iomanip>
#include <vector>
#include <bitset>
 
std::string to_hex(const int32_t number) {
std::stringstream stream;
stream << std::setfill('0') << std::setw(8) << std::hex << number;
return stream.str();
}
 
std::string to_binary(const int32_t number) {
std::stringstream stream;
stream << std::bitset<16>(number);
return stream.str();
}
 
int32_t twos_complement(const int32_t number) {
return ~number + 1;
}
 
std::string to_upper_case(std::string str) {
for ( char& ch : str ) {
ch = toupper(ch);
}
return str;
}
 
int main() {
std::vector<int32_t> examples = { 0, 1, -1, 42 };
 
std::cout << std::setw(9) << "decimal" << std::setw(12) << "hex"
<< std::setw(17) << "binary" << std::setw(25) << "two's complement" << std::endl;
std::cout << std::setw(6) << "-----------" << std::setw(12) << "--------"
<< std::setw(20) << "----------------" << std::setw(20) << "----------------" << std::endl;
 
for ( const int32_t& example : examples ) {
std::cout << std::setw(6) << example << std::setw(17) << to_upper_case(to_hex(example))
<< std::setw(20) << to_binary(example) << std::setw(13) << twos_complement(example) << std::endl;
}
}
</syntaxhighlight>
{{ out }}
<pre>
decimal hex binary two's complement
----------- -------- ---------------- ----------------
0 00000000 0000000000000000 0
1 00000001 0000000000000001 -1
-1 FFFFFFFF 1111111111111111 1
42 0000002A 0000000000101010 -42
</pre>
 
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">let d = 1234567
 
dim b[d * -1, d * -1 + 1, -2, -1, 0, 1, 2, d - 2, d - 1]
 
arraysize s, b
 
for i = 0 to s - 1
 
print b[i], " : ", b[i] * -1
 
next i
 
end</syntaxhighlight>
{{out| Output}}<pre>
-1234567 : 1234567
-1234566 : 1234566
-2 : 2
-1 : 1
0 : 0
1 : -1
2 : -2
1234565 : -1234565
1234566 : -1234566
</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
procedure TwosCompliment(Memo: TMemo);
var N: integer;
begin
N:=123456789;
Memo.Lines.Add(Format('N=%10d $%0.8x',[N,N]));
Memo.Lines.Add('');
Memo.Lines.Add('N:=(N xor $FFFFFFFF)+1');
N:=(N xor $FFFFFFFF)+1;
Memo.Lines.Add('');
Memo.Lines.Add(Format('N=%10d $%0.8x',[N,N]));
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
N= 123456789 $075BCD15
 
N:=(N xor $FFFFFFFF)+1
 
N=-123456789 $F8A432EB
Elapsed Time: 5.206 ms.
</pre>
 
 
=={{header|Forth}}==
{{works with|gforth|0.7.3}}
Forth uses two's complement internally. One can use the 'base' variable to switch from one base to another.
<syntaxhighlight lang="forth">: 2s'complement base @ swap dup negate swap 2 base ! u. u. base ! ;
25 2s'complement</syntaxhighlight>
 
{{out}}
<pre>11001 1111111111111111111111111111111111111111111111111111111111100111 ok
</pre>
 
 
=={{header|FreeBASIC}}==
Line 140 ⟶ 267:
(8#2)#:-3
1 1 1 1 1 1 0 1</syntaxhighlight>
 
=={{header|Java}}==
In Java the two's complement of an integer 'n' is its arithmetic negation '-n'.
 
The two's complement of an integer 'n' can also be calculated by adding 1 to its bitwise complement '~n'.
<syntaxhighlight lang="java">
import java.util.List;
 
public final class TwosComplement {
 
public static void main(String[] args) {
List<Integer> examples = List.of( 0, 1, -1, 42 );
System.out.println(String.format("%9s%12s%24s%34s", "decimal", "hex", "binary", "two's complement"));
System.out.println(
String.format("%6s%12s%24s%32s", "-----------", "--------", "----------", "----------------"));
for ( int example : examples ) {
System.out.println(String.format("%5d%18s%36s%13d",
example, toHex(example), toBinary(example), twosComplement(example)));
}
}
private static String toHex(int number) {
return String.format("%8s", Integer.toHexString(number).toUpperCase()).replace(" ", "0");
}
private static String toBinary(int number) {
return String.format("%32s", Integer.toBinaryString(number)).replace(" ", "0");
}
private static int twosComplement(int number) {
return ~number + 1;
}
 
}
</syntaxhighlight>
{{ out }}
<pre>
decimal hex binary two's complement
----------- -------- ---------- ----------------
0 00000000 00000000000000000000000000000000 0
1 00000001 00000000000000000000000000000001 -1
-1 FFFFFFFF 11111111111111111111111111111111 1
42 0000002A 00000000000000000000000000101010 -42
</pre>
 
=={{header|Jakt}}==
<syntaxhighlight lang="jakt">
fn main() {
let n = 0xabcdeabcdeu64
println("{:064b}", n)
println("{:064b}", ~n + 1)
println("{:064b}", -n) // Same result
}
</syntaxhighlight>
{{out}}
<pre>
0000000000000000000000001010101111001101111010101011110011011110
1111111111111111111111110101010000110010000101010100001100100010
1111111111111111111111110101010000110010000101010100001100100010
</pre>
 
=={{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|M2000 Interpreter}}==
 
 
<syntaxhighlight lang="m2000 interpreter">
Module Complement2{
// we use binary.and to get a number in range of byte 0 to 255
byte k, v
v=random(1, 255) ' there is no two's complement for zero
z=binary.and(binary.not(v)+1, 0xFF)
print v
print z
print z=255-v+1 // z is type of byte always positive
print sint(z+0xFFFFFF00)=-v // using 4bytes, we add unsinged 0xFFFFFF00
}
Complement2
Complement2
</syntaxhighlight>
{{out}}
<pre>
2
254
True
True
208
48
True
True
</pre>
 
=={{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}}==
Line 217 ⟶ 460:
01 FF
</pre>
 
=={{header|Python}}==
<syntaxhighlight lang="python">-n</syntaxhighlight>
or
<syntaxhighlight lang="python">~n+1</syntaxhighlight>
 
=={{header|Quackery}}==
Line 269 ⟶ 517:
By default Rakus integers are arbitrary sized, theoretically of infinite length. You can't really take the twos complement of an infinitely long number; so, we need to specifically use fixed size integers.
 
There is a module available from the Raku ecosystem that provides fixed size integer support, named (appropriately enough.) [https://raku.land/githubzef:thundergnat/FixedInt FixedInt].
 
FixedInt supports fixed bit size integers, not only 8 bit, 16 bit, 32 bit or 64 bit, but ''ANY'' integer size. 22 bit, 35 bit, 191 bit, whatever.
Line 294 ⟶ 542:
761030578771
0b000000000000000001011000100110000111101010001001001010011</pre>
 
=={{header|RPL}}==
RPL can handle integers whose size can be set from 1 to 64 bits. For this task, a 8-bit size is selected with <code>STWS</code>.
RPL considers 'true' integers (i.e. declared by the prefix <code>#</code>) to be positive, so the two's complement can not be done by the <code>NEG</code> instruction.
8 STWS BIN
#3d NOT 1 +
{{out}}
<pre>
1: #11111101b
</pre>
=={{header|Ruby}}==
Ruby integers have a built-in 'one-complement'method: '''~''', which flips all bits. Adding 1 leads to a negative integer:
<syntaxhighlight lang="ruby">~42 + 1 # => -42
</syntaxhighlight>
 
=={{header|Wren}}==
Line 299 ⟶ 561:
 
This is illustrated by running the following code:
<syntaxhighlight lang="ecmascriptwren">var a = 0
a = -a
System.print(a) // -0</syntaxhighlight>
Line 308 ⟶ 570:
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:
 
<syntaxhighlight lang="ecmascriptwren">var pow32 = 2.pow(32)
var pow31 = 2.pow(31)
var bs = [-pow31, -pow31+1, -2, -1, 0, 1, 2, pow31-2, pow31-1]
9,482

edits