1

The openzeppelin provides a data structure library namely BitMaps which can be found here - https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/BitMaps.sol

Can someone explain the logic of what exactly is going on in this library?
Like consider the function get -

    function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
        uint256 bucket = index >> 8;
        uint256 mask = 1 << (index & 0xff);
        return bitmap._data[bucket] & mask != 0;
    }

Here, why is index>>8 done and what does 1 << (index & 0xff) mean?

Could someone clarify this with an example by taking numbers and explaining a use case?

Also, what exactly does the struct Bitmap represents and what does it store?

    struct BitMap {
        mapping(uint256 => uint256) _data;
    }

1 Answer 1

0

The mapping is stored like this -

Buckets - 0,1,2,3,..... 2^256-1
Each bucket stores a 256 digit number which represents whether the corresponding bit is present or absent.

Bucket -> _______________ (256 digit boolean 1 or 0)
0 -> _________________ (256 digit boolean 1 or 0)
1 -> _________________ (256 digit boolean 1 or 0)
2 -> _________________ (256 digit boolean 1 or 0)
3 -> _________________ (256 digit boolean 1 or 0)
.
.
.
.
2^256-1 -> _________________ (256 digit boolean 1 or 0)

Hence, to find the corresponding bucket an index belongs to, index>>8 i.e index/256 is done.
After finding the bucket, the corresponding position for that index inside the bucket is found!

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.