4

Currently I'm using ether.camp to create a contract. At this stage it simply gets and stores some values. However when I try and get the values they are in bytes/hex even though the return type is string?

How do I convert this back to string in the solidity contract? I've tried How to convert a bytes32 to string but no luck

E.g storing "Hello World!" returns 0x0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000c48656c6c6f20576f726c64210000000000000000000000000000000000000000

   contract HelloWorld {
    struct Items {
       address id;
       string data;
    }

    mapping(address => Items) items;

    function getItem(address key) returns (string) {
      return items[key].data;
    }

    function addItem (address key, string data) returns (bool) {
        Items item = items[key];
        item.data = data;
    }

   }

 }

I can see in the ethercamp transactions side bar of the IDE the "Hello World!" is saved as a string but my getItem() just can't retrieve it?

4

Use web3.js like contractInstance.getItem.call(key).

Or mark getItem as constant: function getItem(address key) constant returns (string) and then you can use:

contractInstance.getItem(key)

web3.js will automatically decode the bytes for you. Contracts only have binary data, hex is a more compact way of viewing that data, and that's why you see hex. The binary data is also encoded according to an ABI, so that values can be distinguished, for example between what's just a number and a string.

  • Great thanks! adding constant solves it but I know understand webjs will auto decode it for me – user1202278 Aug 30 '16 at 19:00
  • No problem. (I was going to add more clarification about not needing to "convert this back to string in the solidity contract", and good the answer works for you.) – eth Aug 30 '16 at 19:06
  • Perhaps this merits a new question, but is there an easy one-liner to get the count of Items in the above code? Coming from a .net background I had items.count or items.length in mind. – user1202278 Aug 30 '16 at 20:34
  • 1
    Not the way your code is set up. You can't iterate through a mapping, but if you include an array of addresses, you can get the length of that easily. – Tjaden Hess Aug 30 '16 at 21:16
2

In general, you can also use:

> web3.toUtf8("0x48656c6c6f20576f726c64210000000000000000000000000000000000000000")
Hello World!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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