Search code examples
ethereumsolidity

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


I'am trying to learn about bytes in solidity but it is really confusing. I played around with bytes in remix but one thing in particular is very confusing.

When I tried to assign number 2 to bytes1 like this:

bytes1 public num = 2;

It returned an error.

But when I tried to store 0xb5 like this:

bytes1 public num = 0xb5;

There was no error. I don't have a computer science backround so this may be a trivial question but not for me lol.

Thanks


Solution

  • You can't make implicit type conversion between int literal and bytes. The official solidity documentation says:

    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

    So for this example you can make explicit type conversion of signed integer literal 2, like:

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

    or by using fitted integer hex notation, like:

    bytes1 public num = 0x02;