2

Suppose I have this bytes pad:

0x0123456789abcdef

How can I make it like this:

0xfedcba9876543210

Just by Solidity and not by Assembly.

4

1 Answer 1

1

Based on this answer you can reverse a bytes8 like this:

function reverse(bytes8 input) external pure returns (bytes8 v) {
    v = input;

    // swap nibble (half of an 8-bit byte)
    v = ((v & 0x0F0F0F0F0F0F0F0F) << 4) | 
        ((v & 0xF0F0F0F0F0F0F0F0) >> 4);

    // swap 1-byte
    v = ((v & 0xFF00FF00FF00FF00) >> 8) |
        ((v & 0x00FF00FF00FF00FF) << 8);

    // swap 2-byte long pairs
    v = ((v & 0xFFFF0000FFFF0000) >> 16) |
        ((v & 0x0000FFFF0000FFFF) << 16);

    // swap 4-byte long pairs
    v = (v >> 32) | (v << 32);
}

Compared to the related example where a uint was reversed, I had to swap the nibble because byte is padded to the lower-order (right) while uint are padded to the left (see: bytes).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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