I know bytes32
stores 32 bytes, but what does bytes
store? And what is the difference between the two?
-
3possibly related ethereum.stackexchange.com/questions/11347/bytes-quotes-or-not "bytes and bytes32 are actually very different. bytes is identical to string, whereas bytes32 is identical to uint256."– cryptorenaisanceJan 30, 2017 at 4:36
2 Answers
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;
}
}
-
5
bytes
is not exactly equivalent tobyte[]
. From the docsYou should use bytes over byte[] because it is cheaper, since byte[] adds 31 padding bytes between the elements.
– Ivan PAug 13, 2019 at 16:45 -
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