[Ethereum] How to convert msg.data to a uint

solidity

I am sending ETH to a contract as follows:

web3.eth.sendTransaction({from: sender, to: address, value:amount, gas:300000, data:"1234"});

In my fallback function, I can see msg.data has the following value (as expected):

"0x1234"

The trouble is (and I've been at this for hours…) how do I convert this into a uint holding the value 1234?

Here's my attempt that sorta works (i.e. doesn't):

function bytes2uint(bytes _data) constant returns(uint){
    uint i=0;
    uint dec=0;

    for (i = 0; i < _data.length; i++) {
        byte e=_data[_data.length-i-1];
        uint f=uint(e);
        f=((f/16)*10)+(f%16);
        dec+=(f*(100**i));
    }
    return dec;
}

I am able to successfully convert "0x1234", "0x123456", "0x12", etc. (i.e. an even number of digits). However, when I try "0x123" or "0x12345" (for example), the trailing digit is somehow getting truncated?

Best Answer

You just use

 web3.toHex(1234)

Converting to other types is also supported https://github.com/ethereum/wiki/wiki/JavaScript-API

Related Topic