Skip to main content

Command Palette

Search for a command to run...

strings & Bytes

Published
2 min readView as Markdown
strings & Bytes

Strings

  1. 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";
}
  1. 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.

  2. 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";
}
  1. Strings in solidity does not have length property in storage or memory.

Bytes

  1. In Solidity, bytes is a fixed-size byte array, similar to uint8[] or byte[], but with a fixed length.

  2. 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
    }
}
  1. In the above example, the BytesExample contract demonstrates various operations on bytes arrays. It has a state variable myBytes to store a bytes array, and functions to set, get, concatenate, get substrings, and get the length of bytes arrays.

  2. Note that bytes operations can also be expensive in terms of gas cost, especially if dealing with large bytes arrays, as encoding and decoding binary data can require computational resources.

More from this blog