dfinity / motoko-base

The Motoko base library
Apache License 2.0
481 stars 100 forks source link

Feature Request - Nat support bitwise operation #286

Open BrantBrown opened 3 years ago

BrantBrown commented 3 years ago

Nat64 Nat32 Nat32 Nat8 (except Nat) support bitwise operation. Is there any reason not to support the bit operation of Nat, if not, can you support it?

nomeata commented 3 years ago

Not all operations make sense for Nat, e.g. binary negation is undefined (but it would make sense for Int actually, two-complememt works for arbitrary large numbers as well, where you treat negative numbers as having infinite leading ones in the binary representation). Wouldn't be hardware-speed efficient, and a fair amount of work to implement.

What's your use case, though?

BrantBrown commented 3 years ago

My use case Nat << >> & ^ | .

For example: Convert NatSize (size is 8 16 32 64 except Nat) to [Nat8]

 public func toNat8Array(num: Nat64) : [Nat8] {
      [ Nat8.fromNat(Nat64.toNat((num >> 56) & 0xFF)), 
        Nat8.fromNat(Nat64.toNat((num >> 48) & 0xFF)),
        Nat8.fromNat(Nat64.toNat((num >> 40) & 0xFF)),
        Nat8.fromNat(Nat64.toNat((num >> 32) & 0xFF)),
        Nat8.fromNat(Nat64.toNat((num >> 24) & 0xFF)),
        Nat8.fromNat(Nat64.toNat((num >> 16) & 0xFF)),
        Nat8.fromNat(Nat64.toNat((num >> 8) & 0xFF)),];
    };
rossberg commented 3 years ago

@DelandPro, your example is only using bit ops on Nat64, so should work just fine, as far as I can see.

BrantBrown commented 3 years ago

I mean Nat not support bitwise operation, I want do the something like Nat64

Convert NatSize (size is 8 16 32 64 except Nat) to [Nat8]

@DelandPro, your example is only using bit ops on Nat64, so should work just fine, as far as I can see.