Advanced Operations with Bytes
Aside from the basic operations, you can perform more advanced operations with byte arrays. these are a few examples:
- Concatenating two-byte arrays
- Comparing two-byte arrays for equality
Example:
Solidity
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract AdvancedBytesOperations { // Concatenates two byte arrays function concat(bytes calldata a, bytes calldata b) public pure returns (bytes memory) { bytes memory result = new bytes(a.length + b.length); for (uint i = 0; i < a.length; i++) { result[i] = a[i]; } for (uint j = 0; j < b.length; j++) { result[a.length + j] = b[j]; } return result; } // Compares two byte arrays for equality function equalBytes(bytes calldata a, bytes calldata b) public pure returns ( bool ) { if (a.length != b.length) { return false ; } for (uint i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false ; } } return true ; } } |
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”).