Solidity – Equivalent of Solidity’s bytes32(a_signed_integer) in JavaScript

encodingjavascriptsolidityweb3js

I've got an app that takes various kinds of input via an HTML form, but always ends up sending it to a contract as bytes32. The expectation is that another contract that ultimately consumes the data will cast it into the type that it's expecting, which may be bytes32, uint256 or int256.

For unsigned integers I'm taking a BigNumber object, calling toString(16) on it to get hex, then left-padding it to 64 digits, and appending 0x. But for signed integers, which may be negative, I presumably need to handle the two's complement system; What's the appropriate way to do this?

Best Answer

Using BN.js as suggested by @Ismael:

function numStringToBytes32(num) { 
   var bn = new BN(num).toTwos(256);
   return padToBytes32(bn.toString(16));
}

function bytes32ToNumString(bytes32str) {
    bytes32str = bytes32str.replace(/^0x/, '');
    var bn = new BN(bytes32str, 16).fromTwos(256);
    return bn.toString();
}

function padToBytes32(n) {
    while (n.length < 64) {
        n = "0" + n;
    }
    return "0x" + n;
}