> On Jun 6, 2025, at 21:53, ToddAndMargo via perl6-users <perl6-users@perl.org> 
> wrote:
> 
> Hi All,
> 
> Is there an easy way to print ones' and two's compliment
> of a 32 bit integer?
> 
> Many thanks,
> -T
> 
> 
> sub ones-complement(Int $num) {
>    my $binary = $num.base(2);
>    my $complement = '';
>    for $binary.comb -> $bit {
>        $complement ~= $bit eq '0' ?? '1' !! '0';
>    }
>    return $complement;
> }
> 
> my $number = 5;
> my $complement = ones-complement($number);
> print "Ones complement of $number is $complement\n";
> 
> 
> seems a bit much:
> https://search.brave.com/search?q=raku+print+ones+compliment&source=web&summary=1&conversation=00fda578d0badafdf15143

Seems wrong, too.

1. The code in `sub ones-complement`:
        A. ends in `return $complement`, but should probably end in `return 
$complement.parse-base(2)`.
        B. could be shortened to `$num.base(2).trans(<0 1>=><1 
0>).parse-base(2)`.
        C. Gives the same result of `2` (or binary "010") for inputs of 
5,13,29,61..., which means it is not invertable, so it is probably not the 
droids^Wcode you are looking for.
        D. Might be saved by changing it to `(('0' x 32) ~ 
$num.base(2)).substr(*-32).trans(<0 1> => <1 0>).parse-base(2)`, but there is 
no need, because:
2. Raku has twos-complement built-in, via prefix `+^`.  (Not *infix* `+^`, 
which would be numeric `xor`).
        A. So: `sub twos-complement (Int $num) { return +^ $num }`
        B.     `sub ones-complement (Int $num) { return 1 + 
twos-complement($num) }` # Or would it be `-1` when negative? Depends on if you 
are doing `int` or `uint`? Unsure right now.

See also:
https://docs.raku.org/language/operators#prefix_+^
https://rosettacode.org/wiki/Bitwise_operations#Raku
https://raku.land/zef:thundergnat/FixedInt

-- 
Hope this helps (but I am very sick with a 72-hour bug, so I may have missed 
something important),
Bruce Gray (Util of PerlMonks)

Reply via email to