BigInt and xor
Ivan Kazmenko via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Mar 24 09:35:02 PDT 2015
On Tuesday, 24 March 2015 at 15:45:36 UTC, Dennis Ritchie wrote:
> Tell me, please, how can I replace this code?
>
> import std.conv : to;
> import std.bigint : BigInt;
> import std.string : format;
> import std.stdio : writeln;
>
> void main() {
>
> BigInt[10] bitArr;
>
> ulong n = 18_446_724_073_709_551_614U;
>
> bitArr[0] = format("%b", n).to!BigInt;
>
> writeln(bitArr[0]);
> writeln(bitArr[0] ^ 1); // not work
>
> }
>
> Output:
> 1111111111111111111011011100111101100011000110101011111111111110
> 1111111111111111111011011100111101100011000110101011111111111111
What exactly is not working?
The only thing I see lacking is an ability to print a BigInt in
binary via writefln("%b").
Up to 64 bits, arithmetic and bitwise operations, including xor,
are available with long and ulong. Just print the result as
binary:
-----
import std.stdio;
void main() {
ulong n = ulong.max - 0b1000101;
writeln (n);
writefln ("%b", n);
writefln ("%b", n ^ 1);
}
-----
Output:
-----
18446744073709551546
1111111111111111111111111111111111111111111111111111111110111010
1111111111111111111111111111111111111111111111111111111110111011
-----
If you need more than 64 bits, take a look at BitArray here, it
also has xor defined:
http://dlang.org/phobos/std_bitmanip.html#.BitArray
In the future, please explain what problem you are trying to
solve, as the wrong code alone often leaves one guessing.
Ivan Kazmenko.
More information about the Digitalmars-d-learn
mailing list