Refactor repeated logic to helper method writeBinary