0

How can we efficiently calculate a hash value for a combination of bytes32 and integer value?

Like in JavaScript "someString" + someInt.

I tried:

function fx(bytes32 _left, uint32 _right) public returns (bytes32 hash) {
    hash = keccack256(_left + _right); // wrong
}
1

keccak256 needs a bytes input (dynamic array of bytes). An easy way to convert everything to bytes and concatenate the bytes together is the ABI encoder.

function fx(bytes32 _left, uint32 _right) public pure returns (bytes32 hash) {
    return keccak256(abi.encodePacked(_left,_right)); // right
}

I added pure because this function does not need access to storage and can return a value immediately, without mining, if called by a client. pure is generally the right way to go for such computations.

Hope it helps.

| improve this answer | |
  • Pure clarification was very useful, thanks. – Croll May 16 '19 at 16:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.