Skip to content

Instantly share code, notes, and snippets.

@alexroan
Created October 23, 2020 15:23
Show Gist options
  • Save alexroan/a8caf258218f4065894ecd8926de39e7 to your computer and use it in GitHub Desktop.
Save alexroan/a8caf258218f4065894ecd8926de39e7 to your computer and use it in GitHub Desktop.
bytesSwap.sol
pragma solidity ^0.7.0;
library bytesSwap {
function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {
uint8 i = 0;
while(i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
function stringToBytes32(string memory source) public pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly { // solhint-disable-line no-inline-assembly
result := mload(add(source, 32))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment