1

I am working on a little decentralized game with a world made of plots. It has a map which links a location to a Plot struct. A location is saved as a bytes16 but represents two int64 (coordinates can be negative and the center is in 0, 0). How can I convert them to int64 (it seems I can only convert them to uint64)?

Here is what I tried:

    function convertToCoordinates(bytes32 input)
        public
        pure
        returns (uint128 x, uint128 y)
    {
        bytes16 xbytes;
        bytes16 ybytes;
        (xbytes, ybytes) = split(input);

        x = int128(int128(uint128(xbytes)) - 2**127 - 1);
        y = int128(int128(uint128(ybytes)) - 2**127 - 1);
    }

1 Answer 1

1

Here is a solution:

    function split(bytes32 source) public pure returns (bytes16 x, bytes16 y) {
        bytes16[2] memory output = [bytes16(0), 0];
        assembly {
            mstore(output, source)
            mstore(add(output, 16), source)
        }
        return (output[0], output[1]);
    }

    function convertToCoordinates(bytes32 input)
        public
        pure
        returns (int128 x, int128 y)
    {
        bytes16 xbytes;
        bytes16 ybytes;
        (xbytes, ybytes) = split(input);

        uint128 ux = uint128(xbytes);
        uint128 uy = uint128(ybytes);

        x = int128(ux);
        y = int128(uy);
    }

And since one is not very useful without the other, here is a way to do the opposite:

    function merge(bytes16 sourceA, bytes16 sourceB)
        public
        pure
        returns (bytes32)
    {
        return bytes32((uint256(uint128(sourceA)) << 128) | uint128(sourceB));
    }

    function convertFromCoordinates(int128 x, int128 y)
        public
        pure
        returns (bytes32 output)
    {
        return merge(bytes16(uint128(x)), bytes16(uint128(y)));
    }

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.