I want to convert uint type data to bytes type in solidity. I've found a answer about this which is like below.
function toBytes(uint256 x) public pure returns (bytes memory b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
}
But this doesn't work like what I thought. For example, if I put 0x0000000000000000000000000000000000000000000000000000000000000abc
to the input value, I expected to have a return value which looks like this 0xabc0000000000000000000000000000000000000000000000000000000000000
. But this function returns same as input value which is 0x0000000000000000000000000000000000000000000000000000000000000abc
. How could I convert 0x0000000000000000000000000000000000000000000000000000000000000abc
this to 0xabc0000000000000000000000000000000000000000000000000000000000000
this in solidity?
uint
has bytes0a
andbc
, while resultingbytes
hasab
andc0
.0x0000000000000000000000000000000000000000000000000000000000000abc
to a function, I want to receive0xabc
.0xabc
is not a validbytes
value, as it is 12 bit long, while each byte is 8 bits. So it is fractional number of bytes.0x000000000000000000000000000000000000000000000000000000000000abcd
. I want to receive0xabcd
when I give an input value0x000000000000000000000000000000000000000000000000000000000000abcd
. But that function returns same as input value.