0

I have bytes32 data which needs to be converted into a string, then use to get value from mapping(string => string)

Trying to convert bytes32 to string using : string(abi.encodePacked(temp))

It is working fine:

enter image description here

enter image description here

Mapping contains key value pair : "har0 => "hello"

mapping

But when I uses the same string(converting from bytes32) in mapping to get the value, it doesn't gives value.

enter image description here

enter image description here

1 Answer 1

2

You are trying to decode packed data, which is not possible with abi.decode. As abi.decode can only decode the data that's not packed.

The correct way to decode a bytes input is this

  function convert(bytes memory data) public pure returns (string memory) {
        return abi.decode(data,(string));
    }

And to get the mapping:

function getmap(bytes memory key) public view returns (string memory) {
    return map[convert(key)];
}

try this and it will be working.

In case you really want to work with ancodePacked, you can look into some assembly code for this. Here is a relatable answer : How to decode `encodePacked` data

5
  • Please help me out ! Commented May 4, 2023 at 13:11
  • Did you try what I told you? It's working for me Commented May 5, 2023 at 12:58
  • yes, actually I have tried using with extra zeros at end like 0x68617230 rather than 0x686172300000.. 32 bytes total. It works fine. But I want to use bytes32 actually Commented May 6, 2023 at 16:21
  • Okay, it won't be possible because solidity doesn't have any function to decode packed data. Using assembly can solve your problem. Editing my answer with this update. Commented May 7, 2023 at 9:35
  • Updated the answer, please mark it as answer if it helped you. Commented May 7, 2023 at 9:39

Your Answer

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

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