Dynamically-size Byte Arrays
Dynamic byte arrays do not have a fixed length, and their size can be changed during runtime. These arrays are simply represented by the “bytes” keyword.
Example:
Solidity
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract DynamicBytesExample { // Store a dynamic byte array bytes public dynamicData; // Set the dynamic byte array function setDynamicData(bytes calldata _data) public { dynamicData = _data; } // Get the length of the dynamic byte array function getDynamicDataLength() public view returns (uint256) { return dynamicData.length; } } // Example usage: // setDynamicData input: 0x74657374696e67206461746120666f722064796e616d6963206279746573 // dynamicData output: "testing data for dynamic bytes" // getDynamicDataLength output: 30 |
Explanation:
- The input for the setDynamicData function is a hex-encoded dynamic bytes value: 0x74657374696e67206461746120666f722064796e616d6963206279746573. When converted to a human-readable string, it represents “testing data for dynamic bytes”. This string is 30 characters long, and it’s stored in a dynamic byte array that adjusts its size accordingly.
- When you query the dynamicData variable, the output is the stored data: “testing data for dynamic bytes”.
- When you call the getDynamicDataLength function, it returns the length of the dynamic byte array, which in this case is 30 bytes (the length of the input string).
Output:
Bytes in Solidity
In Solidity, the term “bytes” refers to a dynamically-sized byte array. Solidity provides two types of byte arrays: fixed-size arrays (called “bytesN”, where N is a number between 1 and 32) and dynamic arrays (simply called “bytes”).