2

lets say I have the following uint256 value: 0x70997970c51812dc3a010c7d01b50e0d17dc79c8000403

This uint256 is packed with various data that I would like to be able to parse.

How would I extract the value 4 (third number from the right) or the value 3 (last number)?

1 Answer 1

2

you can use right shift >> in order to move to the rigth the item that you want

for example if you want the index 1 (from rigth to left) you need to move one times to the rigth

and because every hexadecimal value needs 4 bits to be represented you need to multiply by 4

uint move = index * 4;

and then you can use the and operator in order to clear the rest of the numbers

  function getParsed(uint256 value, uint index) external pure returns (uint cleared){
    uint move = index * 4;
    return (value >> move) & 0x000000000000000000000000000000000000000000000000000000000000000f ;        
}

so if you send the parameters:

0x00000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8000403 and 0 you will get the 3

0x00000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8000403 and 1 you will get the 0

0x00000000000000000070997970c51812dc3a010c7d01b50e0d17dc79c8000403 and 1 you will get the 4


if you want to use yul:

   function getParsed(bytes32 value, uint index) external pure returns (uint8 cleared){
     assembly {          
        let move := mul(index,4)
        let shifted := shr(move, value)    
        cleared := and(0x000000000000000000000000000000000000000000000000000000000000000f,shifted)       
    }
}

this line here:

 let move := mul(index,4)

use mul in order to get the multiplication in the our example index = 1 so the result will be 4 (1*4)

and then you need to use shr in order to shift to the rigth

let shifted := shr(move, value) 

and finally we use and in order to clear our value

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.