Skip to content

Instantly share code, notes, and snippets.

@flockonus
Created July 27, 2018 20:57
Show Gist options
  • Save flockonus/cb75838d78cf544744e7ac95ab3ec431 to your computer and use it in GitHub Desktop.
Save flockonus/cb75838d78cf544744e7ac95ab3ec431 to your computer and use it in GitHub Desktop.
/// @dev given a number get a slice of any bits, at certain offset
/// @param _n a number to be sliced
/// @param _nbits how many bits long is the new number
/// @param _offset how many bits to skip
function _sliceNumber(uint256 _n, uint256 _nbits, uint256 _offset) private pure returns (uint256) {
// mask is made by shifting left an offset number of times
uint256 mask = uint256((2**_nbits) - 1) << _offset;
// AND n with mask, and trim to max of _nbits bits
return uint256((_n & mask) >> _offset);
}
ref: https://medium.com/@imolfar/bitwise-operations-and-bit-manipulation-in-solidity-ethereum-1751f3d2e216
@gokulsan
Copy link

Nice concept. Very useful for generating verified randomness on-chain in blockchain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment