40

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

1

2 Answers 2

34

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;
    }
}
2
  • 5
    bytes is not exactly equivalent to byte[]. From the docs You should use bytes over byte[] because it is cheaper, since byte[] adds 31 padding bytes between the elements.
    – Ivan P
    Aug 13, 2019 at 16:45
  • Good catch. :-) Aug 13, 2019 at 17:19
1

http://solidity.readthedocs.io/en/develop/types.html#fixed-size-byte-arrays
Fixed-size byte arrays
bytes1, bytes2, bytes3, …, bytes32. byte is an alias for bytes1.
----------------==
http://solidity.readthedocs.io/en/develop/types.html#dynamically-sized-byte-array
bytes: Dynamically-sized byte array, see Arrays. Not a value-type!
----------------==
bytes _data is a Dynamically-sized byte array, and each element is of type byte1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.