# Can you extract bytesn from bytes in Solidity?

How would you create a Solidity function with the following signature?

``````function extract(bytes data) returns (bytes20 subdata)
``````

Where `subdata` is a contiguous slice of `data` and `data.length > 20`.

This can be with or without inline assembly.

This is the best I've got so far (for the specific case of `n=20`):

``````function extract(bytes data, uint pos) returns (bytes20) {
uint160 subdata = 0;
for (uint160 i = 0; i < 20; i++) {
subdata += uint160(data[i + pos]) * 2 ** (8 * (19 - i));
}
return bytes20(subdata);
}
``````

Drawbacks:

1. limited to `n=20`
2. expensive to compute the powers each time the function is called
3. verbose compared to slicing

Point (2) can be addressed by pre-computing the powers of two (e.g. at contract instantiation). I don't think it is possible to overcome (1) at present in Solidity as return types are strict.

Just an analogue. Not so expensive.

``````function extract(bytes data, uint pos) constant
returns (bytes20 result)
{
for (uint i=0; i<20;i++)
result^=(bytes20(0xff00000000000000000000000000000000000000)&data[i+pos])>>(i*8);
}
``````
• It's a bit cleaner now we have bitshift ops :) – rain Apr 23 '17 at 14:58
• Whats the purpose of the `bytes20(0xff...)`? – Aakil Fernandes Mar 22 '19 at 17:36
• To create a constant with exactly size of 20 bytes. I'm not sure if it is nessesury. But I'm sure it wil work right. – Alexey Barsuk Mar 24 '19 at 8:37