Two's complement: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (Made code moreC++ idiomatic.)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(2 intermediate revisions by 2 users not shown)
Line 285:
for ( int example : examples ) {
System.out.println(String.format("%5d%18s%36s%13d",
String.format("%5d%18s%36s%13d", example, toHex(example), toBinary(example), twosComplement(example)));
}
}
Line 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 561:
 
This is illustrated by running the following code:
<syntaxhighlight lang="ecmascriptwren">var a = 0
a = -a
System.print(a) // -0</syntaxhighlight>
Line 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,483

edits