Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

get range of bytes into fixed-size type #167

Closed
nmushegian opened this issue Oct 22, 2015 · 3 comments
Closed

get range of bytes into fixed-size type #167

nmushegian opened this issue Oct 22, 2015 · 3 comments

Comments

@nmushegian
Copy link

Is there an idiomatic way to put the first 32 bytes of a bytes into a bytes32?

@chriseth
Copy link
Contributor

chriseth commented Nov 6, 2015

There is no way yet. You can use this snippet:

contract c {
    function toBytes32(bytes data, uint index) returns (bytes32) {
        uint val;
        for (uint i = index; i < index + 32; i++)  {
            val *= 256;
            if (i < data.length)
                val |= uint8(data[i]);
        }
        return bytes32(val);
    }
}

@chriseth chriseth closed this as completed Nov 6, 2015
@augustoteixeira
Copy link

Any news on this?

This would be very useful for the following rationale:

  • accessing storage data is very expensive, while accessing contract code is very cheap;
  • this gives a great gas advantage for the use of constants, because they live in the contract's code;
  • value-type constants are not good for storing larger amounts of data;
  • bytes32[20] constant is considered a constant of non-value type;
  • pointers to data defined through bytes constant table = hex"398ba..." are not accessible in assembly (TypeError: Only direct number constants and references to such constants are supported by inline assembly.`);
  • the solution of copying every byte through a loop reduces the gas gains obtained by avoiding storage.

Here are possible solutions:

  • allow the code to get a range of bytes into fixed-size types, like this issue suggests;
  • make bytes32[20] constants possible, like bytes constants currently are;
  • make a pointer to a bytes constant accessible in assembly;

Is there a chance of any of this solutions be made available in the near future?

Is there another solution that I am not seeing?

@cameel
Copy link
Member

cameel commented Apr 25, 2022

If you mean the initial bytes like the original requester, this is now possible with a conversion. See #9170.

If you mean arbitrary slices, then not yet but it's on our roadmap and will be possible eventually. See #7423.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants