Skip to content

Instantly share code, notes, and snippets.

@PatrickAlphaC
Last active October 22, 2020 04:20
Show Gist options
  • Save PatrickAlphaC/35a15b1b573966a2f9d0afc794f82e7c to your computer and use it in GitHub Desktop.
Save PatrickAlphaC/35a15b1b573966a2f9d0afc794f82e7c to your computer and use it in GitHub Desktop.
Two helper functions to deal with bytes
pragma solidity ^0.7.0;
library bytesSwap {
string public test_string = "hello";
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))
}
}
}
@alexroan
Copy link

Can you make this a library, please? The function calls look a lot nicer:

bytes32 someValue;
string stringValue = someValue.bytes32ToString();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment