Last active
October 22, 2020 04:20
-
-
Save PatrickAlphaC/35a15b1b573966a2f9d0afc794f82e7c to your computer and use it in GitHub Desktop.
Two helper functions to deal with bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can you make this a library, please? The function calls look a lot nicer: