0

I am looking to take in a uint256 (in hex notation) and convert it to bytes32. For some reason I am not getting the same value after converting.

function test(uint256 genes1) public returns (bytes32) {      
    bytes32 matron = bytes32(genes1);
    return matron;
}

genes.test.call(0x000063169218f348dc640d171b000208934b5a90189038cb3084624a50f7316c) Return value ----- 0x000063169218f348dd1c457e09cc8e86bd11d156019d255fbe00000000000000

2

Assuming

genes.test.call(0x000063169218f348dc640d171b000208934b5a90189038cb3084624a50f7316c)

is JavaScript, your problem is probably that the parameter is getting interpreted as a JavaScript number, which does not have enough precision to handle numbers as grand as the one you are using. The solidity call therefore gets fed a less precise number, which it correctly casts to bytes32 and returns.

Try quoting the parameter, eg

genes.test.call("0x000063169218f348dc640d171b000208934b5a90189038cb3084624a50f7316c")

Alternatively you could pass a BN or BigNumber instance, eg

genes.test.call(new BigNumber("0x000063169218f348dc640d171b000208934b5a90189038cb3084624a50f7316c"))

The exact syntax you need varies a little bit depending on the web3.js versions and BigNumber / BN.js libraries you're using, but since native JavaScript numbers can't handle the full 256 bits you always need to handle them either as BigNumber/BN objects or as strings of hex beginning with "0x".

-2

I think it's been answered before, but try this bad boy:

function toBytes(uint256 x) returns (bytes b) {
    b = new bytes(32);
    assembly { mstore(add(b, 32), x) }
}
1
  • 1
    Solidity can cast a uint256 to a bytes32 just fine, you shouldn't need to resort to assembly clevers. – Edmund Edgar Dec 2 '18 at 2:30

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.