0

Currently, I am working on a project, I'll get Oracalize response bytes32 string as a hex string. How can I construct hex string back to bytes32 in solidity?

For eg: string value= "0x2a1acd26847576a128e3dba3aa984feafffdf81f7c7b23bdf51e7bec1c15944c"

I want byes32: bytes32 _value=0x2a1acd26847576a128e3dba3aa984feafffdf81f7c7b23bdf51e7bec1c15944c

2
  • Sending a 32-bytes values as strings to a contract and then converting it in Solidity may not be the best idea - basically it's wasted gas. Can you arrange receiving bytes32 or uint256 instead? Same number o bytes, but much cheaper gas-wise.
    – Utgarda
    Sep 15, 2018 at 16:26
  • I've done the conversion to bytes in another question ethereum.stackexchange.com/a/40247, it should not be hard to use bytes32 instead.
    – Ismael
    Sep 15, 2018 at 21:51

1 Answer 1

0
int8[256] p_util_hexdigit =
[ -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
  -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
  -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 ];

  function stringh(bytes memory x) private view returns(bytes32 fc) {
    bytes memory f = new bytes(32);
    for(uint k = 0; k < 32; k++) {
        int8 b = p_util_hexdigit[uint8(x[2*k])];
        f[k] =  byte(b << 4);
        b = p_util_hexdigit[uint8(x[2*k + 1])];
        f[k] |= byte(b);
    }

    assembly {
          fc := mload(add(f, 32))
    }

    return fc;
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.