Created
April 19, 2019 02:18
-
-
Save RJ-software-outsourcing/8ad8f2cb394ac8b25ee31da3de5c61ed to your computer and use it in GitHub Desktop.
Solidity byte <--> uint8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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