0

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

If so, how?

2 Answers 2

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.

1
  • 1
    Nice 👌 yeah that byte placement dependant on type being passed got me. Thanks too 🫡
    – immaxkent
    Jan 24, 2023 at 20:06
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))
    } 
}
3
  • 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, 2023 at 12:58
  • Read this thread ethereum.stackexchange.com/questions/15350/… - 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, 2023 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, 2023 at 14:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.