I have data in zeros and ones only, I want to tightly pack the data and store it to reduce the gas cost. Also I should be able to retrieve the original data from the tightly packed.
pragma solidity ^0.4.17;
contract TightPack {
// gas 422749
uint[] a;
uint[] c;
// function to pack
function pack(uint[] b) public{
uint l = b.length;
delete a;
// Extract first element and allocate a new slot
for(uint i=0;i<l/256;i++){
uint j = i * 256;
uint temp = b[j] << 255;
// b[i] = b[i] << 7;
// Fill until new slot is full i.e 254 values
for(j=j + 1;j < i * 256 + 256;j++){
temp = (b[j] << (255 - (j%256))) | temp;
}
a.push(temp);
}
// if few values are reamining at the end, allocate a new one
if (l%256 > 0){
uint k= (l/256)*256;
uint val = (b[k] << 255);
for(k=k+1; k < l;k++){
val = (b[k] << (255 - (k%256))) | val;
}
a.push(val);
}
}
function unpack() public {
uint l = a.length;
delete c;
// remove a value from array
for(uint i = 0;i < l;i++){
uint temp = a[i];
// Parse the whole value to get 255 values
for(uint j=0;j < 256;j++){
c.push(temp >> (255 - j) & 1);
}
}
}
function get_packed() public view returns(uint[]){
return a;
}
function get_unpacked() public view returns(uint[]){
return c;
}
}
The packing dosent work after 1000 values, while the unpacking doesn't work after 380 values.
What is the reason for this?