motoko icon indicating copy to clipboard operation
motoko copied to clipboard

Implement bitops for Nat and Int

Open crusso opened this issue 4 years ago • 5 comments

A user has requested an infinite precision bitwise negation operator on Nat and Int.

https://forum.dfinity.org/t/how-motoko-uses-the-bitwise-negation-operator/7428/8

Should be easy to support, acc to @nomeata, pointing at:

https://github.com/libtom/libtommath/blob/develop/mp_complement.c

crusso avatar Sep 21 '21 19:09 crusso

(don't forget to check the doc!)

crusso avatar Sep 21 '21 19:09 crusso

@rossberg any reason not to?

crusso avatar Sep 21 '21 19:09 crusso

I think only Int.

Surely not ~ without all the other bitwise operations (category B in https://sdk.dfinity.org/docs/language-guide/language-manual.html#syntax-ops), right? (Although right rotation doesn’t make sense for Int)

nomeata avatar Sep 21 '21 20:09 nomeata

Agreed with @nomeata: only makes sense to do this if we do all the bitops – I changed the issue title accordingly. Also, FWIW, there is no ~ op in Motoko, it's called unary ^. ;)

So I'd expect:

^ : Int -> Int
&, |, >>, << : (Nat, Nat) -> Nat /\ (Int, Int) -> Int
^ : (Int, Int) -> Int

^= : (var Int, Int) -> ()
&=, |=, >>=, <<= : (var Nat, Nat) -> () /\ (var Int, Int) -> ()
^= : (var Int, Int) -> ()

The only ones that make sense for neither Nat nor Int are <<> and <>> (strictly speaking, you could define <<>, but it seems pretty pointless).

So, yes, all doable, but a non-trivial amount of work, and given everything else, not high priority.

rossberg avatar Sep 23 '21 07:09 rossberg

At least we have

shiftLeft : (Nat, Nat32) -> Nat;
shiftRight : (Nat, Nat32) -> Nat;

in the primitives now.

ggreif avatar Jul 16 '24 10:07 ggreif