Bytes Data Type in Solidity

Storing data on the blockchain can be expensive. The Bytes data type is efficient and can also store strings. In most cases bytes cost less gas than the string data type and is the preferred way to store string literals. 

dynamically-sized bytes

Bytes represents a dynamic array of bytes, it is an alias for byte[] and it can accept values of any length. The syntax for declaring bytes data type in Solidity: bytes my_string = 'my_string'; bytes public my_string = 'my_string';

fixed-sized bytes

It is also possible to specify a fixed-sized byte array for 1 to 32 bytes: bytes1 bytes2 ... bytes32. bytes1 public b1 = 'a'; bytes2 public b2= 'aa'; bytes32 public b32 = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; Use the fixed-sized byte array when the length of the value is exactly known. If it's unknown, use the dynamically-sized array by using the bytes data type. If we try to assign a value that's too long for the fixed-sized byte array the compiler will raise an error. TypeError: Type literal_string "AA" is not implicitly convertible to expected type bytes1. Literal is larger than the type.

length of bytes

To find the length of the bytes data type, use the .length() method. It returns the number of characters in the string. // declare mystring as bytes data type bytes public mystring = 'solidity'; // find length of mystring uint public length_of_string = bytes(mystring).length;



Click to jump to section