@dave_stasiuk’s Pack Data and Unpack Data from TreeSloth does this (if I recall correctly). Maybe have a look at those.
Pack Data
Unpack Data