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);  

      }
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.