In other words, how do I ensure that 1 << n does not overflow for n < 256?

At present, I am using uint256(1) << n.

Is there a better way, or is it guaranteed that the expression uint256(1) is replaced with a constant value during compilation (and not computed during runtime)?

Thank you.


According to the Solidity documentation, in the case of 1<<n, 1 will remain arbitrarily precise until converted to non-literal types, so you should be ok.

Number literal expressions retain arbitrary precision until they are converted to a non-literal type (i.e. by using them together with a non-literal expression). This means that computations do not overflow and divisions do not truncate in number literal expressions.

[1] http://solidity.readthedocs.io/en/develop/types.html

  • Well that's funny, I have observed that a simple 1 << n is consistently truncated long before n reaches 256 (didn't quite check when, but I have presumed that it overflows at n == 8, due to the fact that 1 fits in a uint8). – goodvibration Jan 4 '18 at 16:45
  • In fact, here's a warning from Remix, when trying to return 1 << n from a function which returns uint256: "Warning: Result of shift has type uint8 and thus might overflow. Silence this warning by converting the literal to the expected type.". – goodvibration Jan 4 '18 at 16:48

Constants in the source code can be cast with types offering the least precision that will support the value. That can lead to trouble. Unexpected implicit casting in Solidity's exponential operator

You can avoid that kind of trouble by explicitly casting them with high precision.


if(uint(1) < n) {}

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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