Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RJ-software-outsourcing/8ad8f2cb394ac8b25ee31da3de5c61ed to your computer and use it in GitHub Desktop.
Save RJ-software-outsourcing/8ad8f2cb394ac8b25ee31da3de5c61ed to your computer and use it in GitHub Desktop.
Solidity byte <--> uint8
pragma solidity ^0.5.1;
contract Test {
function getRand() view public returns (uint8, uint8, uint8, uint8) {
uint256 t = rand;
bytes memory bb = toBytes(t);
return (toUnit(bb[7]), toUnit(bb[15]), toUnit(bb[23]), toUnit(bb[31]));
}
function toBytes(uint256 x) private pure returns (bytes memory b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
}
function toUnit(byte t) private pure returns (uint8) {
return uint8(t);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment