Implementation of encode and decode