Solidity – How to Define a Constant `bytes32` in Solidity v0.8 and Above

bytes32constantsoliditysolidity-0.8.x

I want to define a constant bytes32 like this:

bytes32 internal constant FOO = bytes32(0x01);

But I'm getting the following error when compiling the code above:

Explicit type conversion not allowed from "int_const 1" to "bytes32".

How can I do this in Solidity v0.8?

Best Answer

You just have to cast the constant values to uint256, like this:

bytes32 internal constant FOO = bytes32(uint256(0x01));

Note that you can also optionally ditch the hexadecimal prefix:

bytes32 internal constant FOO = bytes32(uint256(1));

Though you may want to keep it so that you remember that the value is a bytes32.

Related Topic