// Copyright 2024 RISC Zero, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.9; /// @notice reverse the byte order of the uint256 value. /// @dev Solidity uses a big-endian ABI encoding. Reversing the byte order before encoding /// ensure that the encoded value will be little-endian. /// Written by k06a. https://ethereum.stackexchange.com/a/83627 function reverseByteOrderUint256(uint256 input) pure returns (uint256 v) { v = input; // swap bytes v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >> 8) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >> 32) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >> 64) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /// @notice reverse the byte order of the uint32 value. /// @dev Solidity uses a big-endian ABI encoding. Reversing the byte order before encoding /// ensure that the encoded value will be little-endian. /// Written by k06a. https://ethereum.stackexchange.com/a/83627 function reverseByteOrderUint32(uint32 input) pure returns (uint32 v) { v = input; // swap bytes v = ((v & 0xFF00FF00) >> 8) | ((v & 0x00FF00FF) << 8); // swap 2-byte long pairs v = (v >> 16) | (v << 16); } /// @notice reverse the byte order of the uint16 value. /// @dev Solidity uses a big-endian ABI encoding. Reversing the byte order before encoding /// ensure that the encoded value will be little-endian. /// Written by k06a. https://ethereum.stackexchange.com/a/83627 function reverseByteOrderUint16(uint16 input) pure returns (uint16 v) { v = input; // swap bytes v = (v >> 8) | ((v & 0x00FF) << 8); }