Refactors to_bytes

The original logic was not intuitive.
Changed the code for better readability.

Change-Id: I0d96105d4ff22eed827ed61466a26f69f33addd1