uint number = uint(keccak256(abi.encodePacked(now)) Split each number. For example, if the value of number is 1562, I need to be able to extract the result as: uint a = 1, uint b = 5 , uint c = 6, uint d = 2. What should I do?

2 Answers 2


How about something like this?

pragma solidity ^0.4.24;

contract extractDigits{
    uint8[] digits;

    function generateDigits() public returns(uint){
        delete digits;
        uint number = uint(keccak256(abi.encodePacked(now)));
        uint returnNum = number;
        while (number > 0) {
            uint8 digit = uint8(number % 10);
            number = number / 10;

        return returnNum;

    function getDigit(uint x) public view returns (uint8) {
        return digits[x];

Basically we store the individual digits of a generated number into an array, where the ones place is at element 0, the tens place is at element 1, etc...

The generateDigits() first deletes any existing content in the array (you can handle this differently if you want to keep track of all digits generated over all time). Then it takes the generated number, and loops over it, extracting the last digit in the number (number % 10) and then removing that digit from the end (number / 10).

We store the extracted digit into the array of digits and repeat until there are no more digits left.

You can then retrieve the digits by querying the array as demonstrated in the getDigit() function.

  • Now this is the elaborate version of my "bare essentials" answer :) Commented Oct 17, 2018 at 8:35
  • @Shawn Tabrizi why , Bro . why are you so cool?
    – Kido
    Commented Oct 17, 2018 at 9:41

You can do it with basic arithmetics. You'll find the % "remainder" (https://solidity.readthedocs.io/en/v0.4.24/types.html#integers) operator useful.

Here's an example:

pragma solidity ^0.4.25;
contract Test { 
    function test() public pure returns (uint256, uint256, uint256) {
        uint256 initial = 258;
        // as we are returning integers without decimal places it's always rounded down automatically
        return (initial % 10, initial % 100 / 10, initial % 1000 / 100);

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.