1

In solidity language when I cast string variable to byte32 it show error of Explicit type conversion not allowed from "string memory" to "bytes32" as given in below function

 function testByte32() returns (bytes32)
    {
        string memory data="Hello World";
        return(bytes32(data));
    }

But when I directly convert string to byte32 it works. Its strange behavior is out of my understanding

 function getMsg() public    constant    returns(bytes32 userData)
      {
          bytes32 bb=bytes32("Hello World");
          return(bb);  

      }
Shane Fontaine
  • 18,036
  • 20
  • 54
  • 82
  • Similar: https://ethereum.stackexchange.com/questions/9142/how-to-convert-a-string-to-bytes32 – Eugene Apr 07 '18 at 15:50

1 Answers1

1

Conversion from string to bytes32 is never allowed, because a string can of course be larger than 32 bytes.

In your second example, "Hello World" of type literal_string is never converted to type string, it is directly converted to type bytes32. This is because you declare bb as type bytes32. In your first example however, type literal_string is converted to type string then type bytes32, that is illegal. If you try to increase the string in example 2 to above 31 characters you'll get an error as well.

i.e. conversion of type literal_string to type bytes32 is legal if the literal_string is shorter than 32 characters, but conversion from type string to type bytes32 is never legal, even if the string is shorter than 32.

Theo Port
  • 331
  • 1
  • 6