strings & Bytes

Strings
- Solidity supports String literal using both double quote (") and single quote ('). It provides string as a data type to declare a variable of type String.
pragma solidity ^0.5.0;
contract SolidityTest {
string data = "test";
}
In above example, "test" is a string literal and data is a string variable. More preferred way is to use byte types instead of String as string operation requires more gas as compared to byte operation.
Solidity provides inbuilt conversion between bytes to string and vice versa. In Solidity we can assign String literal to a byte32 type variable easily. Solidity considers it as a byte32 literal.
pragma solidity ^0.5.0;
contract SolidityTest {
bytes32 data = "test";
}
- Strings in solidity does not have length property in storage or memory.
Bytes
In Solidity,
bytesis a fixed-size byte array, similar touint8[]orbyte[], but with a fixed length.It is used to represent sequences of bytes, and is commonly used for binary data manipulation.
Here's an example of how to declare and use bytes in Solidity:
contract BytesExample {
bytes public myBytes; // Public state variable to store a bytes array
function setBytes(bytes memory _data) public {
myBytes = _data; // Set the value of myBytes
}
function getBytes() public view returns (bytes memory) {
return myBytes; // Return the value of myBytes
}
function concatenateBytes(bytes memory _bytes1, bytes memory _bytes2) public pure returns (bytes memory) {
return abi.encodePacked(_bytes1, _bytes2); // Concatenate two bytes arrays
}
function getSubstring(bytes memory _bytes, uint256 _start, uint256 _length) public pure returns (bytes memory) {
bytes memory resultBytes = new bytes(_length); // Create a new bytes array to store the substring
for (uint256 i = 0; i < _length; i++) {
resultBytes[i] = _bytes[_start + i]; // Copy bytes from the original bytes array to the result bytes array
}
return resultBytes; // Return the substring
}
function getBytesLength(bytes memory _bytes) public pure returns (uint256) {
return _bytes.length; // Return the length of the bytes array
}
}
In the above example, the
BytesExamplecontract demonstrates various operations onbytesarrays. It has a state variablemyBytesto store abytesarray, and functions to set, get, concatenate, get substrings, and get the length ofbytesarrays.Note that
bytesoperations can also be expensive in terms of gas cost, especially if dealing with largebytesarrays, as encoding and decoding binary data can require computational resources.




