I have a uint256 that I'm using as a byte array consisting of 10 numbers, 3 bytes each (which takes up 30 bytes, the first 2 bytes of the 32 bytes are ignored):
0x0000aaaaaabbbbbbccccccddddddeeeeeeffffff111111222222333333444444
xxxx^ ^ ^ ^ ^ ^ ^ ^ ^ ^
I need to validate that these numbers are within a certain range. They are uint24 so they are always positive, and the lowest index is 0 so I only really need to check if they are below a certain upper threshold.
At present I am reading the relevant bytes into uint24 objects and checking that the number is below the threshold:
uint256 constant NUM_OF_GROUPS = 129600; // all numbers have to be between 0 and 129599
.......
function decodeAndCheckGroupIndexes(uint256 x)
public
pure
returns (
uint24 a,
uint24 b,
uint24 c,
uint24 d,
uint24 e,
uint24 f,
uint24 g,
uint24 h,
uint24 i,
uint24 j
)
{
assembly {
j := x
mstore(0x1B, x)
a := mload(0)
mstore(0x18, x)
b := mload(0)
mstore(0x15, x)
c := mload(0)
mstore(0x12, x)
d := mload(0)
mstore(0x0F, x)
e := mload(0)
mstore(0x0C, x)
f := mload(0)
mstore(0x09, x)
g := mload(0)
mstore(0x06, x)
h := mload(0)
mstore(0x03, x)
i := mload(0)
}
require(
a < NUM_OF_GROUPS &&
b < NUM_OF_GROUPS &&
c < NUM_OF_GROUPS &&
d < NUM_OF_GROUPS &&
e < NUM_OF_GROUPS &&
f < NUM_OF_GROUPS &&
g < NUM_OF_GROUPS &&
h < NUM_OF_GROUPS &&
i < NUM_OF_GROUPS &&
j < NUM_OF_GROUPS,
"group is out of range"
);
}
however I was wondering if there was a better way to check it involving less computation? This check happens in a loop with an array of uint256 so I'm attempting to achieve maximum efficiency to reduce gas cost.