0

Can you convert a bytes20 to address in assembly (not solidity-typecasting)?

If so, how?

dNyrM
  • 934
  • 6
  • 19

2 Answers2

2

SOLUTION:

If the address is in the first bytes, you can do:

assembly {
    parsed := shr(96, mload(add(data, 32)))
}

With this, you right-shift 96 bits (or 12 bytes), and then assign to an address type.

This solution won't work if you assign to a bytes20 because bytes20 grabs the highest bytes while address the lowest.

dNyrM
  • 934
  • 6
  • 19
0

Yep, heres an example of what the function might look like:

function convertBytes20ToAddress(bytes bytesInput) internal returns (address addressOutput) {
    assembly {
      addressOutput := mload(add(bytesInput,20))
    } 
}
immaxkent
  • 509
  • 2
  • 14
  • You're just leaving an offset of 20 bytes before loading to memory the next 32, so you'd be getting here 12 bytes of 0 left-padding (the rest of the length of the bytes array) plus some of the actual data – dNyrM Jan 23 '23 at 12:58
  • Read this thread https://ethereum.stackexchange.com/questions/15350/how-to-convert-an-bytes-to-address-in-solidity - where someone actually did pretty much the same as me, but others ran into errors in the process and used a different assembly structure. Wdyt? – immaxkent Jan 24 '23 at 10:56
  • This one works (from your link):

    assembly { parsed := shr(96, mload(add(data, 32))) } . I found the answer a couple of days ago, but forgot to update it here. Doing that right now.

    – dNyrM Jan 24 '23 at 14:24