Conversion between little and big endian

This commit is contained in:
Mark Spanbroek 2024-01-22 15:38:25 +01:00 committed by markspanbroek
parent 38411c27ca
commit 1b3b258ccc
3 changed files with 46 additions and 0 deletions

14
contracts/Endian.sol Normal file
View File

@ -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));
}
}
}

10
contracts/TestEndian.sol Normal file
View File

@ -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);
}
}

22
test/Endian.test.js Normal file
View File

@ -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)
})
})