Rewrite INTEGER encoding loop and unit test

The old one was nonsensical. This one's much clearer. Also thing needs
test coverage.