0

I was wondering if it is possible to convert a string to a bytes32 or bytes in solidity like this, I want an input in string and require an equivalent bytes32 and bytes both.

input string = "0x8f54f1c2d0eb5771cd5bf67a6689fcd6eed9444d91a39e5ef32a9b4ae5ca14ff" output bytes32 = 0x8f54f1c2d0eb5771cd5bf67a6689fcd6eed9444d91a39e5ef32a9b4ae5ca14ff

input string = "0xd724b8592f7962a584cfedcacc2e308292f19f5245be8bdecb42354277d3a8674266a8d0b0f2fcdcdc42bc295e2bf6378da440ed7bcb022a154c8a28a825ddb301"

output bytes = 0xd724b8592f7962a584cfedcacc2e308292f19f5245be8bdecb42354277d3a8674266a8d0b0f2fcdcdc42bc295e2bf6378da440ed7bcb022a154c8a28a825ddb301

I have already looked into this link: How to convert a bytes32 to string but this is not working and returning different values than above.

  • The bytes32 equivalence of a string would be the ASCII encoding of that string (not what you're describing in your question). – goodvibration Sep 05 '20 at 17:17
  • What's the use case for this? Can't you just make your function take bytes32 in the first place? That would keep the gas usage a lot lower. – Morten Sep 05 '20 at 17:18
  • I am okay with the gas usage. I want to provide input as a JSON to a function. The Json contains two values as given below: '{"Data":"0x8f54f1c2d0eb5771cd5bf67a6689fcd6eed9444d91a39e5ef32a9b4ae5ca14ff","Signature":"0xd724b8592f7962a584cfedcacc2e308292f19f5245be8bdecb42354277d3a8674266a8d0b0f2fcdcdc42bc295e2bf6378da440ed7bcb022a154c8a28a825ddb301"}'. I get the values from JSON as string. Now I want to convert it to bytes and bytes32 to pass to another function which accepts bytes and bytes32 as an argument. – Pooja M Gupta Sep 05 '20 at 17:37
  • @goodvibration .. i intend to get values as described in the question. Can you please suggest something. I have already tried available solutions but none of them are working – Pooja M Gupta Sep 05 '20 at 17:41
  • You can use https://ethereum.stackexchange.com/questions/39989/solidity-convert-hex-string-to-bytes to convert an hex string into a bytes array. – Ismael Sep 05 '20 at 19:57
  • Thanks Ismael. I tried this solution but it is throwing errors and not working. – Pooja M Gupta Sep 06 '20 at 01:28
  • @PoojaMGupta I've modified the answer to compile with solc 0.5-0.7 it should work now. – Ismael Sep 06 '20 at 18:18
  • Thanks @Ismael. I will verify the solution and let you know. Thanks a lot. – Pooja M Gupta Sep 08 '20 at 01:23
  • I am getting following outputs

    truffle(development)> PG.fromHex(hash1) '0x008f54f1c2d0eb5771cd5bf67a6689fcd6eed9444d91a39e5ef32a9b4ae5ca14ff'

    truffle(development)> hash1 '0x8f54f1c2d0eb5771cd5bf67a6689fcd6eed9444d91a39e5ef32a9b4ae5ca14ff'

    – Pooja M Gupta Sep 08 '20 at 01:30
  • @PoojaMGupta The code doesn't have any error checking. I left that part as exercise. – Ismael Sep 08 '20 at 02:54

0 Answers0