I already know how to convert bytes32ToString and stringToBytes32:
function bytes32ToString(bytes32 x)
public
pure
returns (string memory)
{
bytes memory bytesString = new bytes(32);
uint charCount = 0;
uint j = 0;
for (j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
function stringToBytes32(string memory source)
public
pure
returns (bytes32 result)
{
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
But how to convert string to bytes256 or arbitrary bytes? or convert arbitrary bytes to string?
bytes256
. But you can dobytes(s)
to convert astring
to abytes
orsstring(b)
to convert abytes
to astring
.