Solidity String Conversion – How to Convert a String to Bytes32

bytes32soliditystring

How can I convert a string to a bytes32? Does anyone has a magic function or library which does it?

For example: This works since as input I gave 32-bits. But it won't work with "> 32-bit" chars.

set_txn_hash = a.transact().set("QmVoGzRDscx61k3RHHkLYaMFtxYZi3ps");#32-bit char

function get() returns (stringc value){  
    return list.get_head_data();   
}

But if I need to give more character for example contains 48-bit string this won't work. [Q] How could I make this work?

Best Answer

This has worked for me so far. Not sure if it's the best way.

function stringToBytes32(string memory source) public pure returns (bytes32 result) {
    bytes memory tempEmptyStringTest = bytes(source);
    if (tempEmptyStringTest.length == 0) {
        return 0x0;
    }

    assembly {
        result := mload(add(source, 32))
    }
}

Also, remember that strings in solidity are UTF8 so after converting them to bytes each byte is not necessarily a character.

EDIT: shorter version, should work the same.