0

A similar question has been asked but using web3 in java, however, I would like to encode a string to bytes[] in solidity itself.

4
  • Are you sure you want to go from string to bytes[] ? I guess what you are really looking for is string to bytes ?
    – hroussille
    May 19, 2022 at 17:49
  • @hroussille If I was developing I would use a byte[] i.e. bytes, however the signature for the 3rd party function that I'm using requires a bytes[].
    – MShakeG
    May 19, 2022 at 19:17
  • Could you elaborate on what it is exactly that you want to do ? (with the third party function code if possible)
    – hroussille
    May 19, 2022 at 20:09
  • @hroussille it accepts NFT metadata in that format of max length 100.
    – MShakeG
    May 20, 2022 at 5:28

1 Answer 1

0

Supposing your string comes from an external source (someone outside your contract calls the function with such string as a parameter) you can cast it to bytes and then slice the bytes into an array. Something like this.

contract Cast {

    bytes [] public arr;

    function convertExternalString(string calldata str) external{
        bytes calldata bts =bytes(str);
        for(uint i; i<bts.length; i++){
            arr.push(bts[i:i+1]);
        }
    }

}

Now, if your string is stored on the contract you can also convert it but would have to change the visibility of the function convertExternalString to public and then call it with a this.. The next code works.

contract Cast {

    bytes [] public arr;
    string public st = "Hello";

    function convertInternalString() public {
        this.convertExternalString(st);
    }

    function convertExternalString(string calldata str) public {
        bytes calldata bts =bytes(str);
        for(uint i; i<bts.length; i++){
            arr.push(bts[i:i+1]);
        }
    }

}

Note that calldata slicing is only available for solidity 0.6.0 and above.

3
  • 1
    Thanks, it seems like it'll work, I'll approve on further confirmation.
    – MShakeG
    May 20, 2022 at 11:49
  • So, did it work? May 24, 2022 at 22:33
  • 1
    sorry, haven't yet tested with the 3rd party library, been a bit busy. Should have time by the end of the week.
    – MShakeG
    May 25, 2022 at 6:21

Your Answer

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

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