How to transform bitstring into iodata?

Hi everyone Im facing problems with bitstrings I’m open a folder containing files and have to encode it with Huffman algorithm(huffman | Hex), after encoding I have to save it into an encripted file, but the Huffman.encode functions returns an encoded bitstring and not a binary so I cant save it due to not being an iodata, does anyone have a hint on how to solve this issue

PS I’m using File.write to save a file:
def save_file({encoded, _keys}, filepath, filename) do
IO.inspect(is_bitstring(encoded))
IO.inspect(encoded)
path = filepath <> “/” <> filename <> “.txt”
File.touch!(path)
File.write(path, encoded)
end

Thank you!

The biggest difference between a bitstring and a binary is that the former isn’t evenly divisible into bytes - you need to decide how to pad your data (leading zeros? trailing zeros?) to a multiple of 8 bits.

Do you have a tip on how can I append zeros to it?

You’ll problably need to store the number of bits padded in the file as well, otherwise you won’t be able to reconstruct the original bitstring from the file.

Small example

t = <<3::size(17)>> 
# => <<0, 1, 1::size(1)>>
pad = 8 - (bit_size(t) - (bit_size(t) |> Integer.floor_div(8)) * 8)  
# => 7
<<t::bitstring, 0::size(pad)>>
# => <<0, 1, 128>>

but if that is stored directly to a file, there is no way of knowing how many bits were padded.
So a convention could be to take the first 8-bits to mean the amount of padding that needs
to be removed (as well as the number itself).