Solidity Bit Manipulation – How to Convert uint8 to uint256 Bitmap

bit-manipulationdata-typesmathsoliditytype-casting

Say I have a uint8 with binary value 0000_1001 i.e. 8+1=9 in decimal. How do I convert this uint8 in a gas efficient way to a uint256 which represents a bitmap?, such that in this example the 9th bit(1-indexed) is initialised to 1 and all remaining 255 bits initialised to 0 i.e. ...0_0001_0000_0000

Best Answer

You would use the shift operator.

In your example:

uint8 value = 9;
uint256 mask = 1 << value;

See https://docs.soliditylang.org/en/v0.8.10/types.html#integers