Implicit hexadecimal literal to string conversion

From the official docs:

Hexadecimal literals in some ways behave like string literals but are not implicitly convertible to the string type.


This may not be entirely accurate. I have observed that implicit conversion works fine PROVIDED that hex literal is encoded in UTF-8.

For example:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract Hex {
    function HexToString() public pure returns (string memory x) {
        //x = "hello"
        x = hex"68656c6c6f";

Let me know if its worth while to update the documentation.

Personally I believe this part of the docs is misleading.

As far as I understand, hex"" is more like bytes memory or a sort of literal_bytes and shares very few qualities with string memory. In the case you mentioned, hex"68656c6c6f" is virtually identical to bytes(string("hello")):

keccak256(bytes(string("hello"))) == keccak256(hex"68656c6c6f")

So I think that’s why it works with your code :slight_smile:

1 Like

Yep! What you described makes sense intuitively. Which is what led my to try the code in the first place despite the docs saying it isn’t possible.

1 Like