0

I have the following smart contract to clarify the issue.

pragma solidity ^0.4.17;

contract Test {
    bytes16 number;

    function getNumber() public view returns(bytes16) {
        return number;
    }

    function setNumber(bytes16 _number) public {
        number = _number;
    }
}

So using javascript I convert a number to hex string like so let hex = ‘0x’ + (3456).toString(16) where hex is 0xd80. Then I pass the value as an argument to setNumber. The challenge is when I call getNumber what I receive in return is  0x0d800000000000000000000000000000. Like 28 zeroes is appended to the end. Parsing this gives a wrong value. I parse like so let num = parseInt(‘0x0d800000000000000000000000000000’, 16). And I get 1.7944577943096364e+37. How can one get the right value from this ‘0x0d800000000000000000000000000000’ or how to save the number as bytes16 without the extra zero digits.

0

You need to left pad it. When you pass 0xd80, it is getting right padded as part of the encoding process (to take up 16 bytes).

let argument = "0x" + web3.padLeft("d80", 32);

This should give you 0x00000000000000000000000000000D80

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.