为什么bytes1能存0xb5而solidity不能存2?

Why can bytes1 store 0xb5 but can't store 2 in solidity?

我正在尝试了解 solidity 中的字节,但它确实令人困惑。我在 remix 中玩过 bytes,但有一件事特别令人困惑。

当我尝试像这样将数字 2 分配给 bytes1 时:

bytes1 public num = 2;

返回错误。

但是当我尝试像这样存储 0xb5 时:

bytes1 public num = 0xb5;

没有错误。我没有计算机科学背景,所以这可能是一个微不足道的问题,但对我来说不是哈哈。

谢谢

您不能在 int 文字和字节之间进行隐式 类型转换。官方 solidity documentation 说:

Decimal number literals cannot be implicitly converted to fixed-size byte arrays. Hexadecimal number literals can be, but only if the number of hex digits exactly fits the size of the bytes type. As an exception both decimal and hexadecimal literals which have a value of zero can be converted to any fixed-size bytes type

因此对于此示例,您可以 显式 有符号整数文字 2 的类型转换,例如:

bytes1 public num = bytes1(uint8(2));

或使用适合的整数十六进制表示法,例如:

bytes1 public num = 0x02;

好问题,我没有确切的答案,很乐意讨论。

为了更好地了解差异,假设我们有

bytes1 public hexNum = 0x2;
bytes1 public hexStr = hex"02";
bytes1 public numDecimal = 2;

十六进制或十进制数(numDecimalhexNum)存储 right-aligned(或左填充),因此当转换为字符串时,它看起来像这样:

0x0000000000000000000000000000000000000002

然而,十六进制字符串变量 (hexStr) 保持左对齐,就像 bytes

0x2000000000000000000000000000000000000000

您可以将 hexStr 存储在 bytes1 变量中,但不能存储其他变量,无需显式转换它们来处理对齐问题