pragma solidity ^0.4.26; contract StructSerialization { function StructSerialization() { } event exactUserStructEvent(uint32 staking, string amount); //Use only fixed size simple (uint,int) types! struct ExactUserStruct { uint32 staking; string amount; } function showStruct(ExactUserStruct u) private { exactUserStructEvent(u.staking, u.amount); } function exactUserStructToBytes(ExactUserStruct u) private returns (bytes data) { // _size = "sizeof" u.staking + "sizeof" u.amount uint _size = 4 + bytes(u.amount).length; bytes memory _data = new bytes(_size); uint counter=0; for (uint i=0;i<4;i++) { _data[counter]=byte(u.staking>>(8*i)&uint32(255)); counter++; } for (i=0;i<bytes(u.amount).length;i++) { _data[counter]=bytes(u.amount)[i]; counter++; } return (_data); } function exactUserStructFromBytes(bytes data) private returns (ExactUserStruct u) { for (uint i=0;i<4;i++) { uint32 temp = uint32(data[i]); temp<<=8*i; u.staking^=temp; } bytes memory str = new bytes(data.length-4); for (i=0;i<data.length-4;i++) { str[i]=data[i+4]; } u.amount=string(str); } function test() { //Create and show struct ExactUserStruct memory struct_1=ExactUserStruct(1,"500"); showStruct(struct_1); //Serializing struct bytes memory serialized_struct_1 = exactUserStructToBytes(struct_1); //Deserializing struct ExactUserStruct memory struct_2 = exactUserStructFromBytes(serialized_struct_1); //Show deserealized struct showStruct(struct_2); } }
0.4.26