Solidity – Convert ‘bytes memory’ to ‘bytes8’

bytesmemorysolidity

In solidity, how can I convert bytes memory buffer to bytes8 type?
Example:

bytes8 buf2 = bytes8(memory_buf); // TypeError: Explicit type conversion not allowed

Best Answer

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.