0

I am trying to copy stored values from a map to an array. I have the following code:

pragma solidity ^0.4.21;

contract test {

event LogTest(
    bytes32[5] a
); 

bytes32[5]  arr;    
mapping (uint=>bytes32) attr;

//function that stores values and copies them to array which is returned
function attributes() internal returns(bytes32[5]){
    bytes32[5] x;
    attr[0] = "0x0"; attr[1] = "0x1"; attr[2] = "0x2"; attr[3] = "0x3"; attr[4] = "0x4";

    for(uint i=0;i<5;i++){
        x[i] = attr[i];
    }
    return(x);
}

//function that retrieves stored values and prints them in log
function copy() public {
    arr = attributes();
    LogTest(arr);
}    

}

For some reason I am not getting the correct values copied. I am getting something that looks like this:

"event": "LogTest",
        "args": {
            "0": [
                "0x3078300000000000000000000000000000000000000000000000000000000000",
                "0x3078310000000000000000000000000000000000000000000000000000000000",
                "0x3078320000000000000000000000000000000000000000000000000000000000",
                "0x3078330000000000000000000000000000000000000000000000000000000000",
                "0x3078340000000000000000000000000000000000000000000000000000000000"]
  1. What am I doing wrong? Are the values not even permanently stored in the attributes() function?

  2. Is there a better way to do this than store in a map and copy into an array?

0
  1. What am I doing wrong? Are the values not even permanently stored in the attributes() function?

You are saving the byte representation of the word 0x0, 0x1 etc do: attr[0]=0x0 instead of attr[0]="0x0" (ommit the quotes). That is all.

  1. Is there a better way to do this than store in a map and copy into an array?

This depends on what you are doing. You can save directly on the array.

Hope this helps.

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.