Solidity – How to Assign a Hex Literal to a `bytes` Variable in Solidity

solidity

I am trying to put 0x11 into bytes, but I keep getting an error.

As I know, the bytes type supports the flexible size up to 32 bytes.
However, I do not know what I can't even set 1 byte there.

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;

contract practice {
    bytes1 public a = 0x11;
    bytes  public c = 0x11; // an error occured, why is it??
    bytes public b = '0x11'; // It is not even 0x11, why do I have to put string value into bytes...? 
}

Please let me know this

Best Answer

0x11 is an integer constant. This type is not implicitly convertible to bytes and there's no explicit conversion but you can use bytes.concat() function for that:

bytes public c = bytes.concat(0x11);

In this case, however what you really want is a hexadecimal literal:

bytes public c = hex"11";

bytes public b = '0x11'; // It is not even 0x11, why do I have to put string value into bytes...?

This does not put the number 0x11 in your variable. It puts 0x30783131 in it instead - i.e. the hexadecimal values of the ASCII characters in your string. It's wrong.

Related Topic