In solidity, how can I convert bytes memory buffer to bytes8 type? Example:
bytes8 buf2 = bytes8(memory_buf); // TypeError: Explicit type conversion not allowed
In solidity, how can I convert bytes memory buffer to bytes8 type? Example:
bytes8 buf2 = bytes8(memory_buf); // TypeError: Explicit type conversion not allowed
Using assembly it could look like this (copied and edited from this answer):
function convertBytesToBytes8(bytes inBytes) returns (bytes8 outBytes8) {
if (inBytes.length == 0) {
return 0x0;
}
assembly {
outBytes8 := mload(add(inBytes, 32))
}
}
This is an older inefficient suggestion without using assembly, probably don't use this:
function convertBytesToBytes8(bytes inBytes) returns (bytes8 outBytes8) {
uint256 maxByteAvailable = inBytes.length < 8 ? inBytes.length : 8;
for (uint256 i = 0; i < maxByteAvailable; i++) {
bytes8 tempBytes8 = inBytes[i];
tempBytes8 = tempBytes8 >> (8 * i);
outBytes8 = outBytes8 | tempBytes8;
}
}
Basically it iterates over each of the first 8 bytes in the inBytes array, converts it to a bytes8 variable, then shifts this variable to the right by an appropriate amount, then OR's the variable with the current result (which basically appends it, since the default value for the outBytes8 is all zeros).
I haven't tested either extensively but they seem to work.
This function bytesc8 and try the solidity this :
function getHexString(bytes4 value) pure public returns (string) {
bytes memory result = new bytes(8);
string memory characterString = "0123456789abcdef";
bytes memory characters = bytes(characterString);
for (uint8 i = 0; i < 4; i++) {
result[i * 2] = characters[uint256((value[i] & 0xF0) >> 4)];
result[i * 2 + 1] = characters[uint256(value[i] & 0xF)];
}
return string(result);
}
Please try it
Thank You
outBytes8 := mload(add(inBytes, 8))– Cyril Jul 10 '18 at 10:59function convertBytesToBytes4() public returns (bytes4 outBytes8)and it seems to work but I am not sure. – Thykof Aug 14 '20 at 13:48