Bytes and String in Solidity

1.

If we know the size of the bytes we want to store, the best approach is to use the fixed size byte array type

To initialize a fixed size byte array, we need to specify the size of how many bytes we would like to store.

bytes1 b1 = hex"41";

Bytes can be initialized with either a hex string hex"41" or a hex value 0X41 which is the letter A according to ASCII.

2.

Fixed size bytes can be passed between smart contracts in the Solidity programming language.

3.bytes and bytes32

Bytes is a dynamic array of bytes. It's shorthand for byte[] and you'll see examples of a bytes being treated as an array in code from time to time. myByte[x]. It can have a length of zero and you can do things like append a byte to the end.

Bytes32 is exactly 32 bytes long. It takes exactly one 32-byte word to represent a bytes32 because there's no need to set any space aside to encode the length. The length is always 32. A bytes with 32 bytes of data needs additional encoding to deal with variable length.

4.Converting to bytes

Converting a string to bytes is a straightforward task. We need to initialize bytes passing in the string type. In return, we get a dynamic array of bytes.

bytes memory stringBytes = bytes("This is string");

If we want to convert to the bytes32 type, we need to go to the assembly level and write the string on the memory.

bytes32 result;

assembly {
  result := mload(add("This is string", 32))
}

Keep in mind that we can write only up to 32 bytes.

5.Converting from bytes

In Solidity language, we can convert back the string value to a dynamic size array of bytes. We can’t convert to fixed string bytes because the string type has an unknown size.

bytes memory bytesData = hex"41";
string memory stringData = string(bytesData);
Subscribe to Hicss
Receive the latest updates directly to your inbox.
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.