[Ethereum] Why can I store over 32 characters in bytes32

bytes32solidityweb3js

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

pragma solidity ^0.4.13;

contract Bytes32Test {

    bytes32 msg;

    function add(bytes32 _msg){
        msg = _msg;
    }

    function show() constant returns (bytes32){
        return msg;
    }

}

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

0x736f6d6520737472696e67206f76657220333220636861726163746572732069

the result is "some string over 32 characters i" if we convert it from hex to ascii.

> web3.toAscii("0x736f6d6520737472696e67206f76657220333220636861726163746572732069")
"some string over 32 characters i"

Hope it helps~