3

Is there a simple way to convert a bytes32, e.g. 0xca35b7d915458ef540ade6068dfe2f44e8fa733c, to an address?

bytes32 data = "0xca35b7d915458ef540ade6068dfe2f44e8fa733c";

I tried casting it with address(data) but that didn't work. I've also seen this solution here but that only works with bytes and not bytes32.

Here's the function I need in solidity:

function bytes32ToAddress(bytes32 input) public pure returns(address){
   // convert input to address
   return ...;
}
2

This works fine. Perhaps you were actually including single quotes in your code? If so, remove them.

pragma solidity ^0.4.24;

contract Test {
    function test(bytes32 data) external pure returns (address) {
        return address(data);
    }
}
  • That's not what I am looking for. I edited the question. I want to convert a bytes32 element to an address. – Jambo Dev Jun 10 '18 at 20:06
  • So you have a string with a hexadecimal representation of an address in it? Why? – smarx Jun 10 '18 at 20:06
  • Or if the double quotes are again a mistake, see my edited code. Converting from bytes32 to address is straightforward, but if you actually have a string, that's another matter. – smarx Jun 10 '18 at 20:08
  • I have a function that accepts a bytes32 element. I don't know how to represent a bytes32 element inline. I just put it inside the remix-function in quotes. To be honest I don't even know what bytes32 is. – Jambo Dev Jun 10 '18 at 20:22
  • I made another edit to accept the bytes32 as a parameter. In any case, it all works the same. If you have a bytes32, you can just cast it to address. – smarx Jun 10 '18 at 20:23
2

For solidity 0.5.x you can use

pragma solidity ^0.5.0;

contract Test {
    function test(bytes32 data) external pure returns (address) {
        return address(uint160(uint256(data)));
    }
}

First convert the bytes32 to a uint256, later to uint160(20 bytes) and finaly to addres, this use big endian.

If you want use little endian you should use address(uint160(bytes20(b)))

For more information: solidity doc

1
assembly {
    mstore(0, hash)
    addr := mload(0)
}

Here is an example how to convert public key into address this way: Get address from public key in Solidity

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.