I have a Solidity contract with functions like this:
function SetMessage (bytes32 key, bytes32 message) returns (bool success) {
publicStruct[key].message = message;
return true;
}
function GetMessage (bytes32 key) public constant returns (bytes32) {
var message = publicStruct[key].message;
return message;
}
Then I'll use web3 to execute SetMessage
and then call GetMessage
after that's done:
var mystringmessage = 'some string over 32 characters in length that can seem to be up to 128 characters in length to be stored in bytes32'
var key = 'message key'
MyContract.deployed().then(function (instance) {
contractInstance = instance
return contractInstance.SetMessage(key, mystringmessage, { gas: 200000, from: web3.eth.accounts[0] })
}).then(function () {
return contractInstance.GetMessage.call(key)
}).then(function (messages) {
console.log('MSG: ' + messages[0])
})
It seems that any string up to 128 characters can be stored in one bytes32 object from this. I'm also not converting the ordinary javascript string into bytes32 before executing SetMessage
, or using web3.toAscii
to convert the bytes32 back into a human readable string (as I always thought was necessary). Why should a single bytes32 object be able to store more than 32 characters?
Best Answer
bytes-x(1~32) can store a string, if the length of string is greater than x, then the part out of length will be dropped. It's a simple test contract
and i invoke add function by a param 'some string over 32 characters in length that can seem to be up to 128 characters in length to be stored in bytes32', and now we call show function, the result is
the result is "some string over 32 characters i" if we convert it from hex to ascii.
Hope it helps~