1

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

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

2

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.

  • I dont think it will work much faster with assembly. By the way, it solved my problem. – Alianse777 Jan 30 '18 at 15:32
  • Check the above edit with the assembly version, I'm sure it's more efficient. – willjgriff Jan 30 '18 at 15:39
  • The original example converted to bytes32. In this case for a byte8, I think you should expect outBytes8 := mload(add(inBytes, 8)) – Cyril Jul 10 '18 at 10:59
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.