Fixed-size Byte Arrays (bytesN)
Fixed-size byte arrays have a specified length, ranging from 1 to 32 bytes. The notation “bytesN” is used to represent these arrays, where “N” is an integer representing the length of the array. These arrays are useful when you know the exact size of the data you are working with.
Example:
Solidity
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract FixedSizeBytesExample { // Store a fixed-size byte array bytes32 public fixedData; // Set the fixed-size byte array function setFixedData(bytes32 _data) public { fixedData = _data; } // Get the length of the fixed-size byte array function getFixedDataLength() public view returns (uint256) { return fixedData.length; // Always returns 32 for bytes32 } } // Example usage: // setFixedData input: 0x74657374696e67206461746120666f722062797465733332 // getFixedDataLength output: 32 |
Explanation:
- The input for the setFixedData function is a hex-encoded bytes32 value: 0x74657374696e67206461746120666f722062797465733332. When converted to a human-readable string, it represents “testing data for bytes32”. Note that this string is 22 characters long, but it’s stored in a 32-byte space with extra padding (spaces or zeroes) at the end.
- When you call the getFixedDataLength function, it returns the length of the bytes32 array, which is always 32 bytes.
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”).