dfinity / motoko-base

The Motoko base library
Apache License 2.0
483 stars 99 forks source link

feat: add `bitshiftLeft/Right` to `Nat` #613

Closed ggreif closed 8 months ago

ggreif commented 9 months ago

This is a bit outside of the regular two-argument operator functions, but very useful for fast multiplication (and division) with powers of two.

Provided, so the users don't have to import a primitive.

Things I am not sure about

naming!

Should we mention "shift" at all? If not, what should we say?

I think it is reasonable to use nomenclature as for Nat*.

what about Int?

This can be considered as an infinite stream of digits too when're the suffix (after dropping a certain number of bits) becomes all 0s or all 1s.

Considering this as the (moral) two's complement representation, we could define a similar operation on Int too.

However, proper bignums are using a separate sign bit in the representation, so shifting negative numbers is a more involved operation.