The documentation says:
bytes and string are encoded identically. For byte arrays that store data which is 32 or more bytes long, the main slot stores length * 2 + 1 and the data is stored as usual in keccak256(slot).
I am working with a string (> 31 bytes), a state variable in storage, and am trying to get the location of the data. I am passing the slot number (converted to a bytes variable) to keccak256. It returns a bytes32. How do I use that to find out where the data is stored?
If it matters, I am getting the bytes32 value from this code.
bytes32 data_slot = keccak256 (uint_to_bytes (slot_number));
And the function is defined like this.
function uint_to_bytes (uint value) internal pure returns (bytes memory)
{
uint byte_count = value <= 255 ? 1 : 2;
bytes memory slot_contents = new bytes (byte_count);
uint content_index = 0;
bool value_started = false;
for (int16 b = 31; b >= 0; b--)
{
uint a = uint (b);
uint shift = a * 8;
uint anded_value = (0xff << shift) & value;
uint8 this_byte = uint8 (anded_value >> shift);
if (this_byte > 0)
value_started = true;
if (value_started)
slot_contents [content_index++] = byte (this_byte);
}
return slot_contents;
}
In my case, the base slot number is 5, which contains the length of my string. The length in that slot is correct.
But how do I get the location of the data when keccak256 returns a bytes32. When I convert the bytes32 to a uint256, I get 99383055861825221844433915613614375939768875017829574557572350922731547121557. Certainly that can't be the slot number where the data is.