diff --git a/contracts/Endian.sol b/contracts/Endian.sol new file mode 100644 index 0000000..68fc971 --- /dev/null +++ b/contracts/Endian.sol @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.8; + +contract Endian { + /// reverses byte order to allow conversion between little endian and big + /// endian integers + function _byteSwap(bytes32 input) internal pure returns (bytes32 output) { + output = output | bytes1(input); + for (uint i = 1; i < 32; i++) { + output = output >> 8; + output = output | bytes1(input << (i * 8)); + } + } +} diff --git a/contracts/TestEndian.sol b/contracts/TestEndian.sol new file mode 100644 index 0000000..7ee7df9 --- /dev/null +++ b/contracts/TestEndian.sol @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import "./Endian.sol"; + +contract TestEndian is Endian { + function byteSwap(bytes32 input) public pure returns (bytes32) { + return _byteSwap(input); + } +} diff --git a/test/Endian.test.js b/test/Endian.test.js new file mode 100644 index 0000000..1380323 --- /dev/null +++ b/test/Endian.test.js @@ -0,0 +1,22 @@ +const { expect } = require("chai") +const { ethers } = require("hardhat") + +describe("Endian", function () { + const big = "0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f" + const little = "0x1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100" + + let endian + + beforeEach(async function () { + let Endian = await ethers.getContractFactory("TestEndian") + endian = await Endian.deploy() + }) + + it("converts from little endian to big endian", async function () { + expect(await endian.byteSwap(little)).to.equal(big) + }) + + it("converts from big endian to little endian", async function () { + expect(await endian.byteSwap(big)).to.equal(little) + }) +})