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

Jitendra Kumar. Balla
  • 2,154
  • 1
  • 8
  • 15
  • 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 '18 at 16:26
  • I've done the conversion to bytes in another question https://ethereum.stackexchange.com/a/40247/, it should not be hard to use bytes32 instead. – Ismael Sep 15 '18 at 21:51

1 Answers1

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;
  }