Solidity Data Types – Difference Between `bytes` and `bytes32`

bytesbytes32solidity

I know bytes32 stores 32 bytes, but what does bytes store? And what is the difference between the two?

Best Answer

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.

An important practical difference is that the fixed length bytes32 can be used in function arguments to pass data in or return data out of the contract. The variable length bytes type can be a function argument also, but only for internal use (inside the same contract) because the interface, called the ABI, doesn't support variable length types.

Some possibly disorienting situations are possible if bytes is used as a function argument and the contract successfully compiles. Always use fixed length types for any function that will called from outside.

Hope it helps.

Update:

You can pass variable length string and bytes from Web3 to contracts (and back) but not between contracts, at this time.

pragma solidity ^0.4.11;

contract VariableLength {

    event LogTest(bytes b);

    function test(bytes b) public returns(bool success) {
        LogTest(b);
        return true;
    }
}
Related Topic