0
        uint256 x = 0x12345678;
        uint8 y = uint8(x);
        console2.log(y);

        uint16 y2;
        bytes2 y3;
        assembly {
            let p := mload(0x40)
            mstore(p, x)
            y := mload(p)
            y2 := mload(p)
            y3 := mload(p)
        }
        console2.log(y);
        console2.log(y2);
        console2.log(vm.toString(y3));

Output:

Logs:
  120
  120
  22136
  0x0000000000000000000000000000000000000000000000000000000000000000

The output of y and y2 is as expected(the lowest byte of x), but the output of y3 is all zero, why mload the same slot to uint16 and bytes2 gives totally different result?

(the console2 library is from forge-std)

1 Answer 1

1

bytes2 takes the first two bytes on the left of the number, i.e. the most significant bytes.

Some examples:

bytes2(0x0000000000000000000000000000000000000000000000000000000012345678) = 0x0000

bytes2(0xa763062200000000000000000000000000000000000000000000000012345678) = 0xa763

Your Answer

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

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