1
    CountersUpgradeable.Counter private nonce;

    function mintERC721() ... {
        uint256 tokenId;
        unchecked {
            tokenId = (nonce << 128);
        }
        ...
        nonce.increment();
    }
   

What does (nonce << 128) do? seems like it's creating a very large number. Is it a random number within 128 bit that will never collide when nonce increases every time? Why would this be better than a sequential tokenId increase? i.e. 1,2,3,4, etc

function tokenToNonce(uint256 _tokenId) ... {
    uint256 nonce = _tokenId >> 128;
    if (nonce == 0) {
        return 0;
    }

    return nonce;
}

This one is interesting too, operator now switched to the other way around >>

My understanding is it can find a nonce based on tokenId or 0 if tokenId was not created before?

1 Answer 1

1

That's Bitwise Operations, left shift << and right shift >>. Ideal to manipulate binary bits directly and efficiently.

Learn more about bitwise operations here: https://www.w3schools.com/js/js_bitwise.asp It's a Javascript resource, but bitwise operations behave exactly the same in all the languages that support them.

What the code is doing is left shifting the nonce 128 bits.

Let's use smaller numbers to see it easier.

Let's suppose nonce is 5. Its binary representation is 101. Now, let's left shift it by 1:

tokenId = 5 << 1;

Now, we assigned 5 << 1 tokenId. Its binary representation will be 1010. Notice how the 101 just got moved 1 position to the left. Its decimal value is now 10. You can convert it here: https://www.rapidtables.com/convert/number/binary-to-decimal.html?x=1010

If we left shift 5 by 2: 5 << 2, we get a binary representation like 10100. If we convert it to decimal, we get 20. On each left shift, we basically double the value due to the binary representation.

The right shift operator >> is doing the opposite, shifting the number to the right. If we have 20 >> 2 we get 101, 5, where we started.

As for the reason that code is doing that, I'm not sure, I guess they would have their logical reasons.

I wrote this article about binary representation, it can help you. It does not contain bitwise operations, but helps in understanding binary numbers: https://medium.com/coinsbench/signed-vs-unsigned-integers-binary-representation-overflows-pitfalls-109bc1ef6ef0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.