I would like to take three uints and essentially concatenate them together as one bytes variable. What's the simplest way I can do that? I've seen many posts about people writing full-blown code to merge two bytes together. And that's great, but in my case, if I want to merge 3, I'd have to call that merge function twice which seems inefficient.
I'm familiar with this method which essentially converts a uint to a byte in the simplest way possible.
function toBytes(uint256 x) returns (bytes b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
}
I feel like I should be able to apply this technique to what I'm trying to do. But I haven't been able to figure out how. This method is basically taking one single uint and viewing it as a bytes, which is exactly what I want. Except I would like to say "the first x bytes belong to this uint, and the second x bytes belong to that uint, and the third x bytes belong to this last uint.
Edit: Here's what I have so far. The following code generates this result. Now I just need to figure out how to remove all the extra 0's I do not want.
0x00000000000000000000000000000000000000000000000000000000deadbeefdeadbeefdeadbeef
function testStuff(
uint256 x1, // 3735928559 -> "0xdeadbeef"
uint256 x2, // 3735928559 -> "0xdeadbeef"
uint256 x3 // 3735928559 -> "0xdeadbeef"
) public returns (bytes memory b)
{
b = new bytes(40);
assembly
{
mstore(add(b, 40), x1)
mstore(add(b, 36), x2)
mstore(add(b, 32), x3)
}
}
I want to end up with exactly
0xdeadbeefdeadbeefdeadbeef
I'm not sure if this is the right way to do this. But I'm basically using an expanded bytes object of size greater than 32 so I have enough space to lay out each uint as a byte. Based on the size I set them next to each other. But now I end up with all this extra space that I need to remove.
Yeah my actual values i'll be using for this will be much larger than the 0xdeadbeef example.
– LampShade Apr 14 '20 at 15:02Yes, I understand those hardcoded numbers were for only the 0xdeadbeef example while I was trying to figure out what I was doing wrong.
– LampShade Apr 14 '20 at 15:14mstore(b, 12)as all the threeintstoring operations overwrite the length in the lastbyteof 32 bytes referred to byband we have 0 length if we do not reset. The reason is that EVM writes 32 bytes in memory at a time and each integer storing operations have only 4 bytes occupied on the right side and the rest are zero which overwrite the length on each write operation. "0.....31 bytes 00deadbeefdeadbeefdeadbeef" This is the representation ofb. The last byte of the first 32 bytes have length which is00because of integer writing operations. – Sheraz Arshad Aug 14 '20 at 23:44