A Smart Contract needs to check the uniqueness of a number inside a serie. The serie is specified by a string, and the number by a uint256 type. Is there any easy way on Solidity to compute a hash from these two mixed parameters?

This hash will be very handy to identify uniquely the corresponding items, better than using the string and the number. What will be the best type for the resulting hash? A string or a bytes32? Thx!

  • 2
    From solidy documentation sha3 accepts multiple parameters, so you can do sha3("ehlo", 0x4321). The result of sha3 is bytes32.
    – Ismael
    Oct 16 '17 at 19:42

Another correction (2019-05-17): In modern Solidity version you can no longer pass multiple arguments to keccak256. It now only takes one argument of type bytes. You can still hash multiple values together like this:

function hashSeriesNumber(string calldata series, uint256 number) external pure returns (bytes32)
    return keccak256(abi.encode(number, series));

Correction thanks to @Ismael: The easiest and cheapest way is just to pass multiple arguments to the hashing function:

function hashSeriesNumber(string series, uint256 number) public pure returns (bytes32)
    return keccak256(number, series);

I think the easiest way is to take the hash of the uint256, then take the hash of the string and then xor them together:

function hasher(uint256 i, string str) public pure returns (bytes32)
    return keccak256(i) ^ keccak256(str);

Hashes are usually stored in bytes32, not in a string, because string's cost more gas and the hashing functions return a bytes32 anyways.

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.