Two's complement: Difference between revisions

New post.
No edit summary
(New post.)
Line 183:
(8#2)#:-3
1 1 1 1 1 1 0 1</syntaxhighlight>
 
=={{header|Java}}==
 
<syntaxhighlight lang="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'.
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 ( Integer example : examples ) {
System.out.println(String.format("%5s%18s%36s%13s",
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}}==
884

edits