I have observed something peculiar with the Elixir Base
module. Typically if you have an integer like:
int64 = 586233761406910463
You may wish to convert this to a hexadecimal string like: 822ca7fffffffff
For example, you can do this here:
https://www.binaryhexconverter.com/hex-to-decimal-converter
https://www.binaryhexconverter.com/decimal-to-hex-converter
This site will provide the conventional conversion with these two results. However, Elixir’s Base.encode16
and Base.decode16
do not provide this conventional function.
Unlike also encode32
and decode32
or encode64
and decode64
, the base 16 functions seem uniquely strange in that they pad the resulting string input or output with 0’s to require an even number of string characters.
For example, if you go:
bytes = <<586233761406910463::64>>
# <<8, 34, 184, 127, 255, 255, 255, 255>>
Base.encode16(bytes, padding: false, case: :lower)
# "0822b87fffffffff"
This returns a 0 padded string. If you try to run this in reverse, the 0 pad is also required in reverse:
Base.decode16("822b87fffffffff", padding: false, case: :lower)
# :error
Base.decode16("0822b87fffffffff", padding: false, case: :lower)
#{:ok, <<8, 34, 184, 127, 255, 255, 255, 255>>}
I have casually checked and it seems Base.decode16
requires any input string to have an even number of characters. You must pad any non-even strings with a 0 in front for them to process. Similarly it will always pad any non-even strings with 0 when it returns them.
This is not typical or expected behavior from anything I have encountered before. One can strip the leading 0 when it exists and add leading 0 when string length is odd, but it is peculiar to me. This also does not occur in base32 or base64 processing of this module so it is not expected or consistent.
I cannot find any GitHub for this module to post a bug question/report. It seems perhaps to be part of the Elixir core.
encode32
/ decode32
/ encode64
/ decode64
all have no problem making or receiving odd string lengths as expected.
Why are encode16
and decode16
enforcing even string lengths? If this is a bug, is it anything that can be fixed?
Is this intentional? Thanks for any thoughts.