0

I am working on a Solidity Smart Contract (^0.5.10) where I want to return an array of Ratings elements.

struct Ratings {
    address restaurant
    uint8 score
};

Since returning Rating[], string[], and bytes[] from functions is still experimental, I was attempting to compress the struct into a byte22[] and return that in a serialized format. But I don't know how to combine byteX objects into another byteX object.

I have 3 variables like so:

bytes20 address_string = BytesUtils.toBytes(restaurant.experience);
bytes1 separator = bytes1(";");
bytes1 rating = BytesUtils.toBytes(review.rating);

How can I combine them to create a byte22?

  • A typical solution is to just return two arrays: returns (address[] restaurants, uint8[] scores). – smarx Sep 1 at 22:43
0

The following code can help your purpose.

pragma solidity 0.5.1;

contract A {

    bytes private finalBytes;


    function setBytesCombined() external {
        bytes20 address_string = toBytes(msg.sender);

        bytes1 separator = bytes1(";");

        // Combining.......
        string memory combinedStringEmpty = new string(address_string.length + separator.length);

        bytes memory combinedBytes = bytes(combinedStringEmpty);

        uint iter = 0;

        for (uint i = 0; i < address_string.length; i++) {
            combinedBytes[iter++] = address_string[i];
        }

        for (uint i = 0; i < separator.length; i++) {
            combinedBytes[iter++] = separator[i];
        }

        finalBytes = bytes(combinedBytes);
    }

    function getBytesCombined() public view returns(bytes memory) {
        return finalBytes;
    }

    function toBytes(address a) internal pure returns (bytes20 b) {
        return bytes20(uint160(a));
    }
}

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.