[Ethereum] Build a hash from a string and a number uint256 on Solidity


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!

Best Answer

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.

Related Topic