how do i gas-efficiently check if a bytes32 begins with certain bytes?
the user gives me a bytes32 input, and i want to check if it start with 4 zero bytes.
thank you
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityTesting on remix the cheapest function I got uses 352 gas for execution
function g0(bytes32 x, bytes4 y) public pure returns (bool) {
return bytes4(x) == y;
}
I can't speak to gas efficiency, unfortunately.
From the Solidity docs:
Index access: If
x
is of typebytesI
, thenx[k]
for0 <= k < I
returns thek
th byte (read-only).
So:
function fourLeadingZeroBytes(bytes32 b) public pure returns (bool) {
return b[0] == 0 && b[1] == 0 && b[2] == 0 && b[3] == 0;
}
false
if any of the bytes returned something other than 0
, not just the first 4.
Sep 22, 2020 at 14:11
uint public gasUsed;
, and then you call each solution from a function which starts with uint gasLeft = gasleft();
, and ends with gasUsed = gasLeft - gasleft();
.
Sep 22, 2020 at 14:23
gasUsed
.
Sep 22, 2020 at 14:23
function startsWith(bytes32 x, bytes32 y) pure returns (bool) {return (x & y) == y;}
bytes32
. And you are stating only the type of the first input here!