How to convert Blob to Nat, Nat to Blob?


is there a method to convert a Nat to a Blob?

Otherwise, is there a way to convert Nat to [Nat8]? This would also be a solution because I could then convert [Nat8] to Blob


You could go to Nat64 first with Nat64.fromNat() and then use this library to encode the Nat64 to [Nat8]: at main · aviate-labs/ · GitHub
It lets you choose the byte order you want. You finally get a Blob with Blob.fromArray().

If you don’t know if your Nat fits in 64 bits then you probably have to write it yourself, e.g. looking at one byte at a time with %8 and then dividing by 8, etc.


Here’s small code snippet taken from motoko-sha2/ at master · timohanke/motoko-sha2 · GitHub for the part of converting Nat to [Nat8].

public func fromNat(len : Nat, n : Nat) : [Nat8] {
    let ith_byte = func(i : Nat) : Nat8 {
        assert(i < len);
        let shift : Nat = 8 * (len - 1 - i);
        Nat8.fromIntWrap(n / 2**shift)
    Array.tabulate<Nat8>(len, ith_byte)

You have not know how many bytes you want though and that the number of bytes is sufficient to fit the Nat in there. If you need variable length then something has to be done differently.