[Ethereum] keccak3 in SOLIDITY and in WEB3 different hashes for an address type field

hashkeccaksolidity

How can I get the same resulting hash from Keccak-256 ()in solidity and web3.sha3() in web3?

IN solidity using keccak256( address ) and using web3.sha3 ( address ) gives different results.

In web3 the address field is a string while in solidity it is an address.

How can I convert web3 string to an address type field?

I tried converting the address type field to a string in solidity and I still received different results in hashes.

For address to sting in solidity I used

function toString(address x) returns (string) {
    bytes memory b = new bytes(20);
    for (uint i = 0; i < 20; i++)
        b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
    return string(b);
}

Best Answer

web3.sha3() takes an encoding parameter to specify that you are passing in a hex address:

address_string = '0x5b2063246f2191f18f2675cedb8b28102e957458';
web3.sha3(address_string, {encoding: 'hex'});

As a general side-note: you have to pay gas costs to do any custom work in Solidity so, when possible, you are best off working on the javascript side.