Search code examples
sortingencodingbase64

Does base64 encoding preserve alphabetical ordering?


Let's say I have a list of 100 words, sorted in alphabetical order. If I base64 encode these words, and then order the resulting list again, will the order of the elements be the same?

If not, is there any other encoding algorithm that will provide this behaviour for me?


Solution

  • No, base64 does not preserve sort order of the unencoded strings.

    This is explained in RFC 4648, which also defines an encoding called base32hex, which specifically does guarantee that it maintains sort order.

    If you want to stick with an official standard, base32hex is the best option I'm aware of.

    If the space-efficiency of your encoding is important, though, dropping from base64 down to base32 is a bit of a bummer. If that's the case, you could always create your own encoding (it isn't all that hard) or adopt someone else's (JavaScript example: https://github.com/dominictarr/d64).