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

Viewed 88

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

2 Answers

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;

Nice question, I don't have an exact answer and would love to discuss it.

To see the difference even better, let's suppose we have

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

An hexadecimal or a decimal number (numDecimal or hexNum) is stored right-aligned (or left padded), so when converted to string, it would look something like this:

0x0000000000000000000000000000000000000002

However a hex string variable (hexStr) is kept left aligned, just like bytes

0x2000000000000000000000000000000000000000

You can store hexStr in a bytes1 variable, but not the others, without explicitly converting them to handle alignment issues

Related