Slice numbers in Solidity (For example extract 2 first number from uint)

Viewed 1890

I have this numbers:

uint256 numbers = 123456789;

I need to extract the two first number (12) into uint variable.

Also possibility to extract the next 2 numbers following the previous one: 34

ect.

Is there any easy way to do such thing in solidity ?

I have this function but it is made for strings:

function getSlice(uint256 begin, uint256 end, string text) public pure returns (string) {
    bytes memory a = new bytes(end-begin+1);
    for(uint i=0;i<=end-begin;i++){
        a[i] = bytes(text)[i+begin-1];
    }
    return string(a);    
}

For my case, I want INPUT/OUTPUT numbers will be in UINT256.

Thanks in advance for your help !

2 Answers
  function get2First() public view returns (uint) { 
    
    uint a = 123456789;
    uint b = a / 10000000;       
    return  b ;
}



function get2second() public view returns (uint) {
    
    uint a = 123456789;
    uint b = a / 100000;
    uint c = b % 100;
    return  c ;
}

Or you can make it more readable by using exponents.

The abi encoded returns me an uint whit 77 digits, but I only want the first 16, thus 77 - 16 = 61


contract Twist {
  function cutExtra() public view returns (uint) {
      uint public num = uint(keccak256(abi.encodePacked("KEK")));
      return num/ 10 ** 61;
  }
}
Related