Documenting bytes to fixed bytes conversion.

Co-authored-by: chriseth <chris@ethereum.org>

Co-authored-by: Alex Beregszaszi <alex@rtfs.hu>
This commit is contained in:
Djordje Mijovic
2021-04-23 13:30:19 +02:00
co-authored by chriseth Alex Beregszaszi
parent eb457064b1
commit 337adee395
3 changed files with 26 additions and 8 deletions
+21
View File
@@ -99,6 +99,27 @@ rules explicit::
uint8 d = uint8(uint16(a)); // d will be 0x34
uint8 e = uint8(bytes1(a)); // e will be 0x12
``bytes`` arrays and ``bytes`` calldata slices can be converted explicitly to fixed bytes types (``bytes1``/.../``bytes32``).
In case the array is longer than the target fixed bytes type, truncation at the end will happen.
If the array is shorter than the target type, it will be padded with zeros at the end.
::
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.5;
contract C {
bytes s = "abcdefgh";
function f(bytes calldata c, bytes memory m) public view returns (bytes16, bytes3) {
require(c.length == 16, "");
bytes16 b = bytes16(m); // if length of m is greater than 16, truncation will happen
b = bytes16(s); // padded on the right, so result is "abcdefgh\0\0\0\0\0\0\0\0"
bytes3 b1 = bytes3(s); // truncated, b1 equals to "abc"
b = bytes16(c[:8]); // also padded with zeros
return (b, b1);
}
}
.. _types-conversion-literals:
Conversions between Literals and Elementary Types