ETHEREUM SMART CONTRACTS DEVELOPMENT
Solidity Fundamentals: Types
Value Types: Part Two
In this part, we will be looking at the value types below;
- Fixed-sized byte arrays
- Dynamically-sized value types (bytes, string)
- Enums
Fixed-sized byte arrays — bytes1 (byte), bytes2 … bytes32
The value types bytes1
, bytes2
, …, bytes32
includes a sequence of bytes from 1 to 32. The keyword byte
is alias for byte1
. Beside, fixed-sized value type has got member function named length
which yields the fixed length of the byte array (read only). And also bytes
with a fixed-size variable can be passed between contracts.
The type
byte[]
is an array of bytes, but due to padding rules, it wastes 31 bytes of space for each element (except in storage). It is better to use thebytes
type instead.
We use hex representation to initialize them in Solidity:
bytes1 a = 0x15; // [00010101]
bytes1 b = 0xf6; // [11110110]
Dynamically-sized value types (bytes, string)
Variables of type bytes
and string
are special arrays in solidity.
Bytes
bytes
are used for arbitrary length raw byte data.The length of bytes
is vary from 1 to 32 and treated like an array in solidity. We can push, pop and get the length of the bytes
.
Strings
string
is used to store the arbitrary-length of character set (UTF-8) equal to or more than a byte. It has a dynamic length so can’t be passed between contracts. Furthermore it does not allow length or index access.
string
is not equal tobytes32
but it is equal tobytes
, because its length is dynamic.
Let’s examine below examples for understanding better. Please read comments carefully. Don’t concentrate on code logic but the results of functions to see differences.
Enums
It is used to create user-defined data types, used to assign a name to a constant which makes contracts more readable, maintainable, and less prone to errors. Options of enums
can be represented by unsigned integer values starting from 0. They are explicitly convertible to and from all integer types but implicit conversion is not allowed. enums
require at least one member, and its default value when declared is the first member.
Next we will dive into operators in Solidity. Thanks for reading.