0

I am looking for an option to efficiently convert a string passed to a function as a parameter, interpreted as hex, into bytes. In Solidity.

I.e. doing the same that this piece of code would do

bytes memory b = hex"abcdef1234567890";

just with a string passed as a parameter for a function.

contract C {
  function f(string memory s) public pure returns (bytes memory) {
    bytes memory b;
    ... // read hex-string into b
    return b;
  }
}

Ideally, I'd want something that isn't "manually" looping through the characters of the string in order to translate each into a byte individually as described here: Solidity convert hex string to bytes. Unfortunately, I can't do this off-chain.

Is there such a way?

4
  • What's the reason why you can't do this off chain? As I explained in your previous question, it's a lot more efficient to do it there.
    – Morten
    Jun 17 at 12:25
  • I have an external app I cannot change that will send a string
    – Xenonite
    Jun 17 at 13:23
  • I don't think you can avoid iterating all characters there's no opcode to do that, but the solution in the link can be improved by writing in assembly and removing the bound checks. But I'm with Morten here, it should be done off-chain it will be cheaper in the long run.
    – Ismael
    Jun 19 at 23:55
  • how could/would that be done in assembly?
    – Xenonite
    Jun 21 at 10:40

Browse other questions tagged or ask your own question.