You can find libraries useful for that. Search about memory optimization in Solidity. I’ll do for you as well and when found I’ll post the reference here.
It is a well known approach, not particularly efficient if managed in Solidity, easy to realize using assembly.
Found: read this https://link.medium.com/9cq5nlXqKT
In short it is suggested to write one function which access in writing and one which access in reading using a simple assembly in order to avoid to mask and shift. It is easy to do.